Reputation: 59
I have pojo class as;
public class Person {
private int id;
private String name;
private String address;
private int salary;
// getter and setter
}
I want to convert value of this pojo class object to object array as;
Object[] perObjArray = new Object[4];
empObjArray[0] = personObjcet.getId();
empObjArray[1] = personObjcet.getName();
empObjArray[2] = personObjcet.getAddress();
empObjArray[3] = personObjcet.getSalary();
Like this scenario, i have other pojo classes. I want to create generic method where i can pass pojo object and it will return object array of those values.
I know we can use reflection, but not sure how ? Please help..
Upvotes: 1
Views: 3433
Reputation: 2935
You can solve this via reflection
public Object[] getObjectArray(Person person) throws NoSuchAlgorithmException, IllegalArgumentException, IllegalAccessException {
Field[] fields = person.getClass().getDeclaredFields();
int fieldCount = fields.length;
Object[] objArr = new Object[fieldCount];
for (int i = 0; i < objArr.length; i++) {
Field field = fields[i];
field.setAccessible(true);
objArr[i] = field.get(person);
}
return objArry;
}
to do this via the getters you can do the following via reflection as well
public Object[] getObjectArray(Person person) throws NoSuchAlgorithmException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Method[] methods = person.getClass().getMethods();
List<Method> getters = new ArrayList<>();
for (Method m : methods) {
if (isGetter(m)) {
getters.add(m);
}
}
Object[] objArr = new Object[getters.size()];
for (int i = 0; i < getters.size(); i++) {
Method m = getters.get(i);
objArr[i] = m.invoke(person);
}
return objArr;
}
public static boolean isGetter(Method method){
if(!method.getName().toLowerCase().startsWith("get")) return false;
if(method.getParameterTypes().length != 0) return false;
if(void.class.equals(method.getReturnType()) return false;
return true;
}
Make sure you do your necessary null checks and error handling.
The second method will get all your publically accessible getters in your class and invoke them to retrieve the value.
This also assumes all your getters start with "get" might have to adjust according to your needs.
Upvotes: 3