反射
在运行过程中,对于任意一个类,我们可以知道它的方法和属性;对于任意一个对象,我们可以调用它的方法和属性。这种动态获取信息和动态调用对象方法的功能,我们称为java的反射机制。
For Example:
public class RobotDemo {
public static void main(String[] args) throws Exception{
Class robotClass = Class.forName("domain.Robot"); //加载类
Robot robot = (Robot) robotClass.newInstance(); //获取实例
Field name = robotClass.getDeclaredField("name"); //获取属性
name.setAccessible(true); //在给私有变量赋值之前先设置权限
name.set(robot,"robot1");
Method getHelloSentence = robotClass.getMethod("getHelloSentence", String.class); //getMethod 获取该类的公共方法,包括继承的方法
String finalHello = (String) getHelloSentence.invoke(robot, "welcome");
System.out.println(finalHello);
Method sayHello = robotClass.getDeclaredMethod("sayHello", String.class,Integer.class); //getDeclaredMethod获取本类所有的方法,包括私有的,不含继承的
sayHello.setAccessible(true);
sayHello.invoke(robot,"luhan",1);
}
}
package domain;
public class Robot {
private String name;
public String getHelloSentence(String helloSentence){
return helloSentence + "-" + name;
}
private void sayHello(String personName,Integer num){
System.out.println("hello," + personName + "-" +num);
}
}