1. 程式人生 > >【反射之Method】如何獲取字節碼對象中的方法

【反射之Method】如何獲取字節碼對象中的方法

sta leg instance targe throw tex mem port spa

■獲取字節碼對象的方法有兩種

  第一種:使用字節碼對象獲取所有的方法(只能獲取公有的方法,而不能獲取私有/受保護的方法)

語法:

Class.getMethods()

示例:

Method[] methods = personClass.getMethods();

  第二種:使用字節碼對象獲取對象指定的方法,其參數:1.方法名;2.傳入方法的參數類型加上“.class”

語法:

Class.getMethod(String name, Class<?>... parameterTypes)

示例:

Method setNameMethod = personClass.getMethod("setName", String.class);

■如何調用方法

  調用方法,參數:1.對象(必須明確是哪個對象調用方法); 2.傳入方法中的參數

語法:

Method.invoke(Object obj, Object... args)

示例:

setNameMethod.invoke(p, "寒冰雪");

■如何調用私有構造器呢

  如何能讓對象正常調用私有構造器呢?可以讓獲取到的私有構造器調用setAccessible(Boolean flag),該方法默認是false,即不忽略檢查方法的修飾權限,true則表示忽略檢查方法的修飾權限。將其設置為true即可正常調用了
語法:

setAccessible(boolean flag)

示例:

Constructor<?> constructor2 = personClass.getDeclaredConstructor(int.class);
constructor2.setAccessible(true);
Object p2 = constructor2.newInstance(23);

註:

  若要使用私有方法,一定要先調用getDeclaredMethod()方法獲取到該私有方法(調用getMethod()方法只能獲取到公共的方法,而調用getDeclaredMethod()既能獲取到公共的,也能獲取到私有的和受保護的方法),而後再調用setAccessible()方法。

 1 package reflect_method;
 2 
 3 import java.lang.reflect.Constructor;
 4 import java.lang.reflect.InvocationTargetException;
 5 import java.lang.reflect.Method;
 6 
 7 public class MethodDemo {
 8 
 9     public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
10         Class<?> personClass = Class.forName("reflect.Person");
11         Constructor<?> constructor = personClass.getConstructor(String.class, int.class);
12         
13         Object p = constructor.newInstance("周娟娟", 23);
14         
15         // 使用字節碼對象獲取所有的方法(只能獲取公有的方法,而不能獲取私有/受保護的方法)
16         Method[] methods = personClass.getMethods();
17         for (Method method : methods) {
18             System.out.println(method);
19         }
20         
21         // 使用字節碼對象獲取對象指定的方法,其參數:1.方法名;2.傳入方法的參數類型加上.class
22         Method setNameMethod = personClass.getMethod("setName", String.class);
23         
24         // 調用方法,參數:1.對象(必須明確是哪個對象調用方法); 2.傳入方法中的參數
25         setNameMethod.invoke(p, "寒冰雪");
26         System.out.println(p);
27         
28         Constructor<?> constructor2 = personClass.getDeclaredConstructor(int.class);
29         constructor2.setAccessible(true);
30         Object p2 = constructor2.newInstance(23);
31         System.out.println(p2);
32         
33         Method getAgeMethod = personClass.getDeclaredMethod("getAge");
34         getAgeMethod.setAccessible(true);
35         
36         Object age = getAgeMethod.invoke(p2);
37         System.out.println(age);
38         
39         
40     }
41 
42 }

【反射之Method】如何獲取字節碼對象中的方法