You can use Class#getDeclaredFields() to get all declared fields of this 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 out Sun's tutorial on this .
However, fields do not necessarily all represent VO properties. You prefer to define public methods, starting with get or is , and then calling it to capture the values ββof real properties.
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); } } }
This, in turn, says that there may be more elegant ways to solve your real problem. If you talk a little more about the functional requirement, for which, in your opinion, this is the right solution, we can offer the right solution. Many tools are available to massage the Javabei.
BalusC Jun 07 2018-10-12T00: 00Z
source share