
反射
对于任何一个类,都能知道这个类所有的属性和方法;对于任何一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制
getMethod()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法
getDeclaredMethod()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法
public class Robot {
private String name;
public void sayHi(String hi){
System.out.println(hi+ " "+name);
}
private String throwHello(String tag){
return "hello"+ tag;
}
}
示例:
public class ReflectSample {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class rc = Class.forName("com.example.reflect.Robot");
Robot r = (Robot) rc.newInstance();
//基础
Method getHello = rc.getDeclaredMethod("throwHello",String.class);
getHello.setAccessible(true);
Object str = getHello.invoke(r,"Bob");
System.out.println("getHello result is " + str);
//公共
Method sayHi = rc.getMethod("sayHi", String.class);
sayHi.invoke(r,"welcome");
Field name = rc.getDeclaredField("name");
name.setAccessible(true);
name.set(r,"Alice");
sayHi.invoke(r,"welcome");
}
}
————————————————
版权声明:本文为CSDN博主「loulanyue_」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/loulanyue_/article/details/103568496