Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the fields in an Object via reflection?

I have an object (basically a VO) in Java and I don't know its type.
I need to get values which are not null in that object.

How can this be done?

like image 484
Swapna Avatar asked Jun 07 '10 12:06

Swapna


People also ask

How do you find the value of field using 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.

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

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

How do you find the field value?

The GetFieldValue method retrieves the current value of a field. The method returns the value of the field represented by FieldObject into the variable you specify. The value of variable can be a data type that can be nullable or an instance of a user class.


1 Answers

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow(); for (Field field : someObject.getClass().getDeclaredFields()) {     field.setAccessible(true); // You might want to set modifier to public first.     Object value = field.get(someObject);      if (value != null) {         System.out.println(field.getName() + "=" + value);     } } 

To learn more about reflection, check the Sun tutorial on the subject.


That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {     if (Modifier.isPublic(method.getModifiers())         && method.getParameterTypes().length == 0         && method.getReturnType() != void.class         && (method.getName().startsWith("get") || method.getName().startsWith("is"))     ) {         Object value = method.invoke(someObject);         if (value != null) {             System.out.println(method.getName() + "=" + value);         }     } } 

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

like image 186
BalusC Avatar answered Sep 18 '22 14:09

BalusC