java.lang.Class.getDeclaredMethod()方法详解

java.lang.Class.getDeclaredMethod()方法用法

注:方法返回一个Method对象,它反映此Class对象所表示的类或接口的指定已声明方法。


描述

java.lang.Class.getDeclaredMethod()方法返回一个Method对象,它反映此Class对象所表示的类或接口的指定已声明方法。


name 参数是一个字符串,指定所需的方法的简单名称,

parameterTypes 参数是一个数组的Class对象识别方法的形参类型,在声明的顺序



声明

  1. public Method getDeclaredMethod(String name, Class... parameterTypes) throws NoSuchMethodException,SecurityException  



参数
name -- 方法的名称
parameterTypes -- 参数数组


返回值
匹配指定名称和参数的类的方法,此方法返回的Method对象


异常
NoSuchMethodException -- 如果匹配方法未找到

NullPointerException -- 如果name 为 null.


SecurityException -- If a security manager, s, is present.


实例
如何使用java.lang.Class.getDeclaredMethod()方法


 

  1. package com.app.ui;  
  2.   
  3. import java.lang.reflect.*;  
  4.   
  5. public class ClassDemo {  
  6.   
  7.    public static void main(String[] args) {  
  8.       
  9.      ClassDemo cls = new ClassDemo();  
  10.      Class c = cls.getClass();  
  11.   
  12.      try {  
  13.         // parameter type is null  
  14.         Method m = c.getDeclaredMethod("show", null);  
  15.         System.out.println("method = " + m.toString());   
  16.       
  17.         // method Integer  
  18.         Class[] cArg = new Class[1]  
  19.         cArg[0] = Integer.class;  
  20.         Method lMethod = c.getDeclaredMethod("showInteger", cArg);  
  21.         System.out.println("method = " + lMethod.toString());  
  22.   
  23.      }catch(NoSuchMethodException e){  
  24.         System.out.println(e.toString());  
  25.      }  
  26.    }  
  27.   
  28.   
  29.    private Integer show() {  
  30.       return 1;  
  31.    }  
  32.       
  33.    public void showInteger(Integer i) {  
  34.       this.i = i;  
  35.    }  
  36.    public int i = 78655;  
  37. }  




编译和运行程序,产生以下结果:

  1. method = private java.lang.Integer ClassDemo.show()  
  2. method = public void ClassDemo.showInteger(java.lang.Integer)  



注:

getDeclaredMethod() 获取的是类自身声明的所有方法,包含public、protected和private方法。

getMethod () 获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。

转载于:https://www.cnblogs.com/6060b/p/4246904.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值