2

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");

        }
4

1 回答 1

3

Just use getDeclaredMethods() and it will give you only the methods of the actual runtime object (i.e. considering dynamic binding) excluding inherited methods.

The problem that getMethods() retrieves inherited methods as well.

于 2013-03-02T06:05:29.613 回答