mardi 8 janvier 2019

How to invoke child class method from parent class through reflection

I want to create a menu which should be populated by arbitrary methods, which are marked by an annotation. The methods should be invoked from inside the base class. Unfortunately 'java.lang.ClassCastException' is thrown since the method.invoke function expects an object which is instance of the child class. But i only get the base class.

Here is what i tried so far :

public abstract Class BaseClass{

    private void invokeSomeMethod(){
        final Method[] methods= getClass().getDeclaredMethods();

        for (Method method : methods) {
            if (method.isAnnotationPresent(MenuFunction.class)) {
                MenuFunction menuFunction = method.getAnnotation(MenuFunction.class);
                menuFunction.invoke(this); //Throws 'java.lang.ClassCastException' 
            }
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ METHOD })
    public @interface MenuFunction {
        String Label();
    }

}

public Class ChildClass extends BaseClass{

     @MenuFunction(Label = "First method")
    public void setHigh(){
      //Arbitrary function 
    }

    @MenuFunction(Label = "Another method")
    public void setLow(){
      //Do something
    }

}





Aucun commentaire:

Enregistrer un commentaire