public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException {
//获取Class字节码
Class<Person> c = Person.class;
//调用构造函数创建对象
Person p = c.getConstructor(String.class,int.class).newInstance("zhangsan",20);
//获取方法设置姓名
Method m = c.getMethod("setName", String.class);
//设置姓名为lisi
m.invoke(p, "lisi");
// 获取年龄属性
Field f = c.getDeclaredField("age");
//取消权限
f.setAccessible(true);
//设置年龄
f.set(p, 25);
System.out.println(p);
}
}
class Person{
private String name;
private int age;
Person(){}
Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
|