Using the reflection API, POJO fields can be obtained as shown below. The inherited class may find the problem here.
TestClass testObject= new TestClass().getClass(); Fields[] fields = testObject.getFields(); for (Field field:fields) { String name=field.getName(); System.out.println(name); }
Or, using the Reflections API, you can also get all the methods in the class and iterate over it to find the attribute names (standard POJO methods start with get / is / set) ... This approach worked for me for the Inherited class structure.
TestClass testObject= new TestClass().getClass(); Method[] methods = testObject.getMethods(); for (Method method:methods) { String name=method.getName(); if(name.startsWith("get")) { System.out.println(name.substring(3)); }else if(name.startsWith("is")) { System.out.println(name.substring(2)); } }
However, a more interesting approach is below:
Using the Jackson library, I was able to find all the properties of a class of type String / integer / double and the corresponding values ββin the Map class. (all without using api reflections!)
TestClass testObject = new TestClass(); com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper(); Map<String,Object> props = m.convertValue(testObject, Map.class); for(Map.Entry<String, Object> entry : props.entrySet()){ if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){ System.out.println(entry.getKey() + "-->" + entry.getValue()); } }
Amit kaneria
source share