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

本文介绍了如何使用Java反射机制来设置对象的属性值。通过两种方法实现:直接操作Field对象和调用对象的方法。这两种方式均能成功修改私有属性,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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})。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值