java使用反射给对象属性赋值的两种方法


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反射机制ClassMethod这些类。 动态调用的方法: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})。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM