具有接口的枚举类成员在内部找不到方法 [英] Enum class member with interface cannot find methods internally
问题描述
public class ClassWithEnum {
private MyEnum myEnum;
//尝试在内部访问它会抛出错误
public boolean isActionable(){
return myEnum.isActionable();
}
public enum MyEnum实现Action {
ACTIONABLE(){
@Override
public boolean isActionable(){return true;
},
NOT_ACTIONABLE(){
@Override
public boolean isActionable(){return false; }
}
}
public interface Action {
public boolean isActionable();
}
}
现在,这是最初的工作,但现在编译器正在抱怨(我已经在一个全新的项目中尝试了相同的结果),错误:
java :/Users/kcoppock/Documents/Projects/EnumInterfaceTest/src/com/example/EnumInterfaceTest/ClassWithEnum.java:11:找不到符号
符号:方法isActionable()
location:class com.example。 EnumInterfaceTest.ClassWithEnum.MyEnum
我以前做过这些(使用界面定义的行为枚举)没有问题。任何想法?
您需要实现 isActionable()
MyEnum
本身。因为在 ACIONABLE
和 NOT_ACTIONABLE
isActionable() >是他们本地的。所以你需要一个全局的方法来为 MyEnum
枚举
。
使用这个代码:
public enum MyEnum implements Action {
ACTIONABLE(){
@覆盖
public boolean isActionable(){return true;
},
NOT_ACTIONABLE(){
@Override
public boolean isActionable(){return false; }
};
@Override
public boolean isActionable(){return false;}
}
I'm having a strange issue which I'm not sure if it's a compiler problem or my understanding of enums with interfaces. I'm using IntelliJ IDEA 12, building an Android project, and I have a class like this:
public class ClassWithEnum {
private MyEnum myEnum;
//Trying to access it internally here throws the error
public boolean isActionable() {
return myEnum.isActionable();
}
public enum MyEnum implements Action {
ACTIONABLE() {
@Override
public boolean isActionable() { return true; }
},
NOT_ACTIONABLE() {
@Override
public boolean isActionable() { return false; }
}
}
public interface Action {
public boolean isActionable();
}
}
Now, this was working initially, but now the compiler is complaining (and I've tried this in a brand new project as well with the same results) with the error:
java: /Users/kcoppock/Documents/Projects/EnumInterfaceTest/src/com/example/EnumInterfaceTest/ClassWithEnum.java:11: cannot find symbol
symbol : method isActionable()
location: class com.example.EnumInterfaceTest.ClassWithEnum.MyEnum
I've done this before (enumerations with behaviors defined by an interface) with no issues. Any thoughts?
You need to implement isActionable()
method in MyEnum
itself. Because the method isActionable()
defined inside the ACIONABLE
and NOT_ACTIONABLE
are local to them . So you need the global method for the MyEnum
enum
.
use this code instead:
public enum MyEnum implements Action {
ACTIONABLE() {
@Override
public boolean isActionable() { return true; }
},
NOT_ACTIONABLE() {
@Override
public boolean isActionable() { return false; }
};
@Override
public boolean isActionable() { return false;}
}
这篇关于具有接口的枚举类成员在内部找不到方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!