利用反射机制获取对象不同修饰符的属性。
private属性需暴破后对值进行更改
package test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/**
* 利用反射获得对象的属性
*/
public class Test {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException {
//先获取Person类的Class对象
Class<?> personClass = Class.forName("test.Person");
//
Object person = personClass.getDeclaredConstructor().newInstance();
//获取public修饰的属性
Field name = personClass.getField("name");
//通过反射操作属性
name.set(person, "john");
System.out.println(person); //Person{name='john', age=0}
//获取非public修饰的age属性
Field age = personClass.getDeclaredField("age");
//对age进行暴破操作
age.setAccessible(true);
age.set(person, 30);
System.out.println(person); //Person{name='john', age=30}
Field sex = personClass.getDeclaredField("sex");
//对sex进行暴破操作
sex.setAccessible(true);
sex.set(null, 1); //因为sex是static属性,所有Person类对象都只使用一个静态成员变量,因此 person 也可写成 null
System.out.println(sex.get(null)); //此处同理
}
}
class Person {
public String name;
private int age;
private static int sex;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}