Field获取反射对象字段及暴力反射
public class Demo_Reflect {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("com.demo.Person");
Constructor c = cls.getConstructor(String.class,int.class);
Person p = (Person) c.newInstance("张三",23);
Field f = cls.getDeclaredField("name");// 获取反射对象的字段(如果字段为私有使用getDeclaredField,如果为公有则使用getFeild)
f.setAccessible(true);// 去除私有权限
f.set(p, "李四");
System.out.println(p);
}
}
class Person {
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
private String name;
private int age;
public Person(String Name, int Age) {
name = Name;
age = Age;
}
}