Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection: how to get field value from an object, not knowing its class

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?

like image 254
svz Avatar asked Apr 23 '13 14:04

svz


People also ask

How do you find the value of field in a reflection?

Field. get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.

Is it possible to get information about private fields methods using reflection?

Yes it is possible.

How do you find the object of a class using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.

How do you find the declared field of a class?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


1 Answers

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

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

like image 63
Charlie Avatar answered Sep 21 '22 17:09

Charlie