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