package ReflectTest; public class Dog { private final String name; private final int sex; private final int weight; private final String type; public Dog(String name, int sex, int weight, String type) { this.name = name; this.sex = sex; this.weight = weight; this.type = type; } public String getName() { return name; } public int getSex() { return sex; } public int getWeight() { return weight; } public String getType() { return type; } @Override public String toString() { return "{"name":"" + name + "","sex":"" + sex + "","weight":"" + weight + "","type":"" + type + ""} "; } }
package ReflectTest; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Run { public static void main(String[] args) throws Exception { // 性别: 0:母, 1:公 Dog dog = new Dog("点点", 0, 25, "哈士奇"); System.out.println(dog.toString()); Class<? extends Dog> clazz = dog.getClass();// 获取到对象对应的class对象 Field[] fields = clazz.getDeclaredFields();// for (Field f : fields) { String fileName = f.getName(); int m = f.getModifiers(); String mStr = Modifier.toString(m); System.out.println(fileName + " 属性:" + mStr); } // 把上面已经创建好的狗狗的名字改为:大大 Field nameField = clazz.getDeclaredField("name");// 获取私有成员变量:name nameField.setAccessible(true);// 设置操作权限为true nameField.set(dog, "大大"); Field typeField = clazz.getDeclaredField("type"); typeField.setAccessible(true); typeField.set(dog, "金毛"); System.out.println(dog.toString()); } }