通过反射访问类中成员
- 根据方法名和参数列表获取
Method
方法对象:Method m = clazz.getDeclaredMethod(方法名, XX.class);
- 获取对象:
Object o=clazz.newlnstance();
- 暴破:
m.setAccessible(true);
- 访问:
Object returnValue = m.invoke(o,实参列表);
- 注意:如果是静态方法,则
invoke
的参数 o
,可以写成 null
package reflection_;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectAccessMethod {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException {
Class<?> boosCls = Class.forName("reflection_.Boss");
Object o = boosCls.newInstance();
Method hi = boosCls.getDeclaredMethod("hi", String.class);
hi.invoke(o, "Gin Sherry");
Method say = boosCls.getDeclaredMethod("say", int.class, String.class, char.class);
say.setAccessible(true);
System.out.println(say.invoke(o, 356, "Gin", 'A'));
System.out.println(say.invoke(null, 356, "Vodka", 'B'));
Object reVal = say.invoke(null, 4869, "Vermouth", 'S');
System.out.println("reVal 的运行类型 " + reVal.getClass());
}
}
class Boss{
private static String name;
public int age;
public Boss() {
}
private static String say(int n, String s, char c){
return n + " " + s + " " + c;
}
public void hi(String s){
System.out.println("hi" + s);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/02fe5d6cc16019d6b97d64b9baad8ffe.png)