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?
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.
Yes it is possible.
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.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With