1.利用反射实例化对象:
Person aPerson =new Person();
Class class1 = aPerson.getClass();
try {
Person c1 = aPerson.getClass().newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.利用反射拿到实例域的值
Person aPerson =new Person();
Class class1 = aPerson.getClass();
try {
Person c1 = aPerson.getClass().newInstance();
Field field = class1.getDeclaredField("name");
field.setAccessible(true);
field.get(c1);
System.out.println(field.get(c1));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.利用反射拿到方法
Person aPerson =new Person();
Class class1 = aPerson.getClass();
try {
Person c1 = aPerson.getClass().newInstance();
Method aMethod =Person.class.getDeclaredMethod("setAge",int.class);
Method bMethod =Person.class.getDeclaredMethod("getAge");
int age =(int)bMethod.invoke(c1);
System.out.println(age);
aMethod.invoke(c1,12);
System.out.println(c1.getAge());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}