Java反射:如何从一个对象中获取字段值,而不知道它的类 [英] Java reflection: how to get field value from an object, not knowing its class
问题描述
比如说,我有一个方法可以返回一个带有一些对象的自定义 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
,这就变得很容易了,因为迭代器可以给你类型信息:
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屋!