Java 使用反射给属性赋值
package com.nf147.manage.spring;
import java.lang.reflect.Field;
public class Cat {
private String name;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
public String setname() {
return name;
}
public static void main(String[] args) throws Exception {
//第一种方式
Cat cat = new Cat();
Field name = cat.getClass().getDeclaredField("name");
name.setAccessible(true);
name.set(cat, "波斯猫");
System.out.println(cat.name);
//第二种方式
Cat cat1 = Cat.class.newInstance();
cat1.name = "中华田园猫";
System.out.println(cat1.name);
}
}
结果如图:
www.cnblogs.com/nongzihong/p/10120104.html