Java的反射:
Robot.java:
package 包.reflect; public class Robot { private String name; public void sayHi(String helloSen) { System.out.println(helloSen + ":" + name); } private String throwHello(String tag) { return "private Hello:" + tag; } }
ReflectDemo.java:
package 包.reflect; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectDemo { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException { Class rc = Class.forName("包.reflect.Robot"); Robot r = (Robot) rc.newInstance(); System.out.println("class name is :" + rc.getName()); // 获取声明的方法 // getDeclaredMethod获取不到:继承的方法和实现接口的方法 Method getPrivateHello = rc.getDeclaredMethod("throwHello", String.class); getPrivateHello.setAccessible(true); Object str = getPrivateHello.invoke(r, "bob"); System.out.println("getHello result is :" + str); // getMethod获取 类自己的public方法,集成类的方法和实现接口的方法 Method sayHi = rc.getMethod("sayHi", String.class); sayHi.invoke(r, "welcome"); // 设置name Field name = rc.getDeclaredField("name"); name.setAccessible(true); name.set(r, "Alace"); sayHi.invoke(r, "welcome"); } }
运行结果:
class name is :qihoo.qtest.mqtt.reflect.Robot getHello result is :private Hello:bob welcome:null welcome:Alace