I have following two classes
public abstract class A {
public String p1;
public String p2;
// Includes getters/setters
}
public class B extends A {
public String p3;
public String p4;
// Some implementation to populate base class attributes
// Includes getters/setters
}
public static void main(String[] args) {
// Initializing and populating parameters for B
System.out.println(B.getP1());
System.out.println(B.getP2());
}
How can print all the elements of the base class B
without invoking individual getters for the attributes in main
. Since there is a possibility that in future class A
will have additional attribute that will require using getter method again in main
for that attribute. All I want is to print all the attributes from the Base class only.
CodePudding user response:
You should be able to do that by iterating over the attributes of the base class using reflection.
import java.lang.reflect.Field;
class B {private String p1="1"; private String p2="2";}
class A extends B {private String p3="3"; private String p4="4";}
public class Scratch {
static void showFields(Class clazz, Object obj) throws Exception {
for(Field f:clazz.getDeclaredFields()) {
f.setAccessible(true);
System.out.println("Field " f.getName() " had value " f.get(obj));
}
}
public static void main(String[] args) throws Exception {
System.out.println("Fields defined in parent: ");
showFields(B.class, new A());
System.out.println("Fields defined in child");
showFields(A.class, new A());
}
}
So I tested this and it works for me--but I run java 8. I just did a little looking around and it looks like they might be removing the ability to setAccessable in a later version (Or maybe just from the core java classes.. need to experement).
The other possibility is to read from public methods instead of members. Use getDeclaredMethods() instead of getDeclaredFields() and your array will have to be an array of Method. Instead of calling .get(obj) call .invoke(obj). Make sure that the method didn't take any parameters (Getters won't take parameters), there is a parameter count in the Method object that will tell you if it takes parameters. If you start with this code don't forget to add getters to A and B.
As long as the getter methods are public, this should work. At least this code should give you some place to start.
Please let me know how this works for you, I will soon have to migrate a lot of code forward and it's going to be a lot harder if this doesn't work any more.