在 Java 中根據名稱和引數型別獲取宣告的方法
可以使用 java.lang.Class.getDeclaredMethod() 方法根據名稱和引數型別獲取宣告的方法。此方法接受兩個引數,即方法的名稱和方法的引數陣列。
getDeclaredMethod() 方法返回一個 Method 物件,該物件表示與方法名稱和引數陣列(作為引數)匹配的類的該方法。
以下給出了一個使用 getDeclaredMethod() 方法根據名稱和引數型別獲取宣告方法的程式示例:
示例
package Test; import java.lang.reflect.*; public class Demo { public String str; private Integer func1() { return 1; } public void func2(String str) { this.str = "Stars"; } public static void main(String[] args) { Demo obj = new Demo(); Class c = obj.getClass(); try { Method m1 = c.getDeclaredMethod("func1", null); System.out.println("The method is: " + m1.toString()); Class[] argument = new Class[1]; argument[0] = String.class; Method m2 = c.getDeclaredMethod("func2", argument); System.out.println("The method is: " + m2.toString()); } catch(NoSuchMethodException e){ System.out.println(e.toString()); } } }
輸出
The method is: private java.lang.Integer Test.Demo.func1() The method is: public void Test.Demo.func2(java.lang.String)
現在讓我們瞭解一下上面的程式。
在 Demo 類中,有兩個方法 func1() 和 func2()。演示此方法的程式碼片段如下:
public String str; private Integer func1() { return 1; } public void func2(String str) { this.str = "Stars"; }
在 main() 方法中,建立了一個 Demo 類的物件 obj。然後使用 getClass() 獲取 obj 的類 c。最後,使用 getDeclaredMethod() 方法獲取方法 func1() 和 func2(),並顯示它們。演示此方法的程式碼片段如下:
Demo obj = new Demo(); Class c = obj.getClass(); try { Method m1 = c.getDeclaredMethod("func1", null); System.out.println("The method is: " + m1.toString()); Class[] argument = new Class[1]; argument[0] = String.class; Method m2 = c.getDeclaredMethod("func2", argument); System.out.println("The method is: " + m2.toString()); }
廣告