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?
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.
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");
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.
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.
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