java.lang.Class.getDeclaredMethod()方法用法
注:方法返回一個Method對象,它反映此Class對象所表示的類或接口的指定已聲明方法。
描述
java.lang.Class.getDeclaredMethod()方法返回一個Method對象,它反映此Class對象所表示的類或接口的指定已聲明方法。
name 參數是一個字符串,指定所需的方法的簡單名稱,
parameterTypes 參數是一個數組的Class對象識別方法的形參類型,在聲明的順序
聲明
- 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()方法
- package com.app.ui;
- import java.lang.reflect.*;
- public class ClassDemo {
- public static void main(String[] args) {
- ClassDemo cls = new ClassDemo();
- Class c = cls.getClass();
- try {
- // parameter type is null
- Method m = c.getDeclaredMethod("show", null);
- System.out.println("method = " + m.toString());
- // method Integer
- Class[] cArg = new Class[1]
- cArg[0] = Integer.class;
- Method lMethod = c.getDeclaredMethod("showInteger", cArg);
- System.out.println("method = " + lMethod.toString());
- }catch(NoSuchMethodException e){
- System.out.println(e.toString());
- }
- }
- private Integer show() {
- return 1;
- }
- public void showInteger(Integer i) {
- this.i = i;
- }
- public int i = 78655;
- }
編譯和運行程序,產生以下結果:
- method = private java.lang.Integer ClassDemo.show()
- method = public void ClassDemo.showInteger(java.lang.Integer)
注:
getDeclaredMethod() 獲取的是類自身聲明的所有方法,包含public、protected和private方法。
getMethod () 獲取的是類的所有共有方法,這就包括自身的所有public方法,和從基類繼承的、從接口實現的所有public方法。