I am assigning a child class object to a parent class reference. Using reflection i want to access the child class setter methods. I am able to get the child class setter methods but getting the setter method of parent class object too. I am explicitly checking the parent class setter method by hard coding the method names now. How can I avoid this?
public abstract class A {
String val;
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
}
public class B extends A{
String valB;
public String getValB() {
return valB;
}
public void setValB(String valB) {
this.valB = valB;
}
}
A a = new B();
for (Method method : a.getClass().getMethods()){
if (isSetter(method) && !(checkUnwantedMethods(method.getName()))) {
method.invoke(a, "someValue");
}
}
public static boolean isSetter(Method method){
if(!method.getName().startsWith("set")) return false;
if(method.getParameterTypes().length != 1) return false;
return true;
}
public boolean checkUnwantedMethods(String methodName){
return (methodName.equals("setVal");
}