黑马程序员技术交流社区
标题:
我这反射程序的错误在哪?运行不了
[打印本页]
作者:
meihua
时间:
2015-11-6 07:36
标题:
我这反射程序的错误在哪?运行不了
package protect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
@SuppressWarnings("unchecked")
Class<Person> clazz=(Class<Person>) Class.forName("protect.Person");
Field field=clazz.getDeclaredField("age");
field.setAccessible(true);
Person p1=clazz.newInstance();
field.set(p1, 15);
Object obj1=field.get(p1);
System.out.println(obj1);
Method method=clazz.getMethod("show", null);
Constructor<Person> cons=clazz.getConstructor(String.class,int.class);
Person p2=cons.newInstance("小明",18);
method.invoke(p2, null);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Person{
public String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public void show(){
System.out.println(name+age);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2