java中如何访问类中的字段,Java:如何通过存储在变量中的名称访问类的字段?...

How can I set or get a field in a class whose name is dynamic and stored in a string variable?

public class Test {

public String a1;

public String a2;

public Test(String key) {

this.key = 'found';

}

}

解决方案

You have to use reflection:

Use Class.getField() to get a Field reference. If it's not public you'll need to call Class.getDeclaredField() instead

Use AccessibleObject.setAccessible to gain access to the field if it's not public

Use Field.set() to set the value, or one of the similarly-named methods if it's a primitive

Here's an example which deals with the simple case of a public field. A nicer alternative would be to use properties, if possible.

import java.lang.reflect.Field;

class DataObject

{

// I don't like public fields; this is *solely*

// to make it easier to demonstrate

public String foo;

}

public class Test

{

public static void main(String[] args)

// Declaring that a method throws Exception is

// likewise usually a bad idea; consider the

// various failure cases carefully

throws Exception

{

Field field = DataObject.class.getField("foo");

DataObject o = new DataObject();

field.set(o, "new value");

System.out.println(o.foo);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值