Java反射:如何从对象获取字段值,而不知道它的类 [英] Java reflection: how to get field value from an object, not knowing its class

查看:1378
本文介绍了Java反射:如何从对象获取字段值,而不知道它的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个方法可以返回带有一些对象的自定义 List 。它们以 Object 的形式返回给我。我需要从这些对象中获取某个字段的值,但我不知道对象的类。

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.

有没有办法通过Reflecion或其他方式做到这一点?

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

推荐答案

假设一个简单的案例,你的字段是 public

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).

如果你可以改变你的方法来返回 List< ; Foo> ,这变得非常简单,因为迭代器可以为您提供类型信息:

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

List<Foo> list; //From your method
for(Foo foo:list) {
    Object fieldValue = foo.fieldName;
}

或者如果你正在使用没有泛型的Java 1.4接口,但是你知道应该在列表中的对象的类型......

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;
   }
}

无需反思:)

这篇关于Java反射:如何从对象获取字段值,而不知道它的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆