【反射之Method】如何获取字节码对象中的方法

■获取字节码对象的方法有两种

  第一种:使用字节码对象获取所有的方法(只能获取公有的方法,而不能获取私有/受保护的方法)

语法:

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 }
原文地址:https://www.cnblogs.com/snow1234/p/7219671.html