尝试 - 抓住Enum

时间:2016-10-01 13:20:41

标签: java

我想在Enum中保存一个方法,但Class.getDeclaredMethod抛出NoSuchMethodException,那么我该如何处理呢? 我的代码:

public enum Card {

OPENPRISON(false, Cards.class.getDeclaredMethod("", Player.class));

private boolean isInstant;
private Method method;

private Card(boolean isInstant, Method method){
    this.method = method;
    this.isInstant = isInstant;
}

public boolean isInstant() {
    return isInstant;
}

public void run(Player p){

}

}

和OPENPRISON是问题

2 个答案:

答案 0 :(得分:1)

一个直接的技术问题是,您在致电getDeclaredMethod()时没有提供方法名称:

OPENPRISON(false, Cards.class.getDeclaredMethod("", Player.class));

更大的问题是你需要使用反射的原因。

枚举值是常量。使用静态方法无法轻易做到的反射怎么办?或者使用枚举之外的方法?

答案 1 :(得分:0)

那么你的代码会抛出一个检查过的异常,所以你可以使用一个方法:

OPENPRISON(false, foo());

private static Method foo() {
    try {
        return Cards.class.getDeclaredMethod("", Player.class);
    } catch (NoSuchMethodException e) {
        return null;
    }
}

当然,问题仍然存在,如果没有反思就无法解决问题 - 很可能是有可能的。

相关问题