java反射获取对象值,Java反射:如何从对象获取字段值,而不知道它的类

Say, I have a method that returns a custom List with some objects. They are returned as Object to me. I need to get value of a certain field from these objects, but I don't know the objects' class.

Is there a way to do this via Reflecion or somehow else?

解决方案

Assuming a simple case, where your field is public:

List list; // from your method

for(Object x : list) {

Class> clazz = x.getClass();

Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.

Object fieldValue = field.get(x);

}

But this is pretty ugly, and I left out all of the try-catches, and makes a number of assumptions (public field, reflection available, nice security manager).

If you can change your method to return a List, this becomes very easy because the iterator then can give you type information:

List list; //From your method

for(Foo foo:list) {

Object fieldValue = foo.fieldName;

}

Or if you're consuming a Java 1.4 interface where generics aren't available, but you know the type of the objects that should be in the list...

List list;

for(Object x: list) {

if( x instanceof Foo) {

Object fieldValue = ((Foo)x).fieldName;

}

}

No reflection needed :)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值