Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Java Reflection to print out attributes of the parent class?

is it possible to use Java Reflection to print out the attributes of a parent class.

like image 617
Oh Chin Boon Avatar asked Dec 12 '22 12:12

Oh Chin Boon


2 Answers

Yes, you could do something like this:

Class<?> parentClass = getClass().getSuperclass();

Field[] fields = parentClass.getDeclaredFields();
for (Field field : fields) {
    System.out.println("field: " + field.getName());
}

Method[] methods = parentClass.getDeclaredMethods();
for (Method method : methods) {
    System.out.println("method: " + method.getName());
}
like image 126
WhiteFang34 Avatar answered Mar 08 '23 23:03

WhiteFang34


Given an appropriately permissive security policy, it is possible to print out any class/instance's attributes using reflection. See How to limit setAccessible to only "legitimate" uses? for some interesting discussion.

like image 38
Dilum Ranatunga Avatar answered Mar 08 '23 22:03

Dilum Ranatunga