我想创建一个菜单,该菜单应使用任意方法填充,并用注释标记。这些方法应从基类内部调用。不幸的是,由于method.invoke
函数需要一个作为子类实例的对象,因此引发了“ java.lang.ClassCastException”。但是我只能得到基类。
这是我到目前为止尝试过的:
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
}
}
答案 0 :(得分:0)
我猜你想做的是这样
公共抽象类BaseClass {
public void invokeSomeMethod() throws InvocationTargetException, IllegalAccessException {
final Method[] methods = getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MenuFunction.class)) {
MenuFunction menuFunction = method.getAnnotation(MenuFunction.class);
method.invoke(this); //invoke method here'
}
}
}
}
public class ChildClass extends BaseClass{
@MenuFunction(Label = "hello")
public void hello() {
System.out.println("hello");
}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
new ChildClass().invokeSomeMethod();
}
}
结果:
你好