1,常见问题
(1)比如下面的代码:
public void demo() throws Exception { Class class1 = Class.forName("com.imooc.reflect.test.Goods"); Constructor c1 = class1.getConstructor(); Goods goods = (Goods) c1.newInstance(); goods.display(); Constructor c2 = class1.getConstructor(String.class, String.class, Float.class, String.class); Goods goods1 = (Goods) c2.newInstance("aaa", "x", 3, "x"); goods1.display();}(Goods类的属性就这四个,三个String,一个Float)
可是,当运行就会报错。
原来:
(2)忽略对私有属性的
setAccessible(true);在对私有属性进行操作之前,要设置权限比如:
Class class1 = Class.forName("com.imooc.address.Address"); Address addr = (Address) class1.newInstance(); Method method = class1.getDeclaredMethod("display"); method.invoke(addr); Method method1 = class1.getDeclaredMethod("info"); method1.setAccessible(true); method1.invoke(addr); Method method2 = class1.getDeclaredMethod("equalsAddress", String.class); method2.setAccessible(true); method2.invoke(addr, "abc");