Java 使用反射給屬性賦值
阿新 • • 發佈:2018-12-14
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);
}
}
效果: