java反射無所不能,辣麼,怎麼通過反射設置一個屬性的值呢?
主程序:
/**
* @author tengqingya
* @create 2017-03-05 15:54
*/
public class TestReflectSet {
private String readOnly;
public String getReadOnly() {
return readOnly;
}
public void setReadOnly( String readOnly ) {
System.out.println("set");
this.readOnly = readOnly;
}
}
方法1:
TestReflectSet t = new TestReflectSet();
Field f = t.getClass().getDeclaredField("readOnly");
f.setAccessible(true);
f.set(t, "test");
System.out.println(t.getReadOnly());
以上方法得到一個類的Field 屬性,然後設置可見性,然後設置了一個值,最後打印
方法2:
Method setReadOnly = t.getClass().getMethod("setReadOnly", String.class);
String s ="test2";
setReadOnly.invoke(t,s);
System.out.println(t.getReadOnly());
最後的打印結果:
調用方法一
test
調用方法二
set
test2
也就是說,第一種方法,沒有調用屬性的set方法就完成了賦值,但是第二種方法,是通過調用屬性的set方法來完成賦值。
所以,如果想在程序中改變程序的屬性的值的同時還想做一些額外的事情,可以將這些事情寫到set方法中並使用第二種方法哦················