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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
方法1:
TestReflectSet t = new TestReflectSet(); Field f = t.getClass().getDeclaredField("readOnly"); f.setAccessible(true); f.set(t, "test"); System.out.println(t.getReadOnly());
- 1
- 2
- 3
- 4
- 5
以上方法得到一個類的Field 屬性,然后設置可見性,然后設置了一個值,最后打印
方法2:
Method setReadOnly = t.getClass().getMethod("setReadOnly", String.class); String s ="test2"; setReadOnly.invoke(t,s); System.out.println(t.getReadOnly());
//---------------------------------------------------------------------------------
可以用到java反射機制,Class和Method這些類。 動態調用的方法:a.getClass().getMethod(str, new Class[]{}).invoke(a, new Object[]{})
其中,a為類的對象,str為要被調用的方法名 。
1、a.getClass()得到a.class 對象 ;
2、getMethod(str, new Class[]{})得到a對象中名為str的不帶參數的方法;
如果str方法帶參數如str(String s, int i),就要這樣寫getMethod(str, new Class[]{String.class,int.class}) 。
3、invoke(a,new Object[]{})調用方法,第一個參數是要調用這個方法的對象,如果方法是static的,這個參數可以為null
如果調用有參數的方法str(String s, int i),應該這樣寫:invoke(a,new Object[]{"jimmy", 1})。