1、准备工作,创建一个Dog类。
package com.zjl.study.反射;
public class Dog {
private String name;
private int age;
private String color;
public static String school;
public static final String SCHOOL_NAME = "宠物学校";
public Dog() {
}
public Dog(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}
2、成员变量赋值取值操作代码
package com.zjl.study.反射;
import org.junit.Test;
import java.lang.reflect.Field;
public class 获取Class类的成员变量赋值 {
@Test
public void setField() throws Exception {
Class<Dog> dogClass = Dog.class;
Field nameField = dogClass.getDeclaredField("name");
Dog dog = new Dog();
nameField.setAccessible(true);
nameField.set(dog, "金毛");
System.out.println(dog);
String name = (String) nameField.get(dog);
System.out.println("name " + "======>" + name);
}
}
3、运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/69da2d535d4198bb7d3d7683aa5b9261.png)