现在,我有一个各种值的枚举,我想知道是否有任何方法可以在枚举中存储方法。例如:
public enum myEnum{
one("first", callFirstMethod),
two("second", callSecondMethod),
three("last", callThirdMethod);
public String message;
public Method met;
myEnum(String m, Method meth){
message = m;
met = meth;
}
}
public class myMethods{
public void callFirstMethod(){
System.out.println("First!");
}
public void callSecondMethod(){
System.out.println("Second!");
}
public void callThirdMethod(){
System.out.println("Third!");
}
}
然后使用类似的东西: 方法method = myEnum.one.callFirstMethod();
调用方法。这样的事情可能吗?我试过在谷歌上玩/环顾四周,没有什么事实真的出现了。谢谢你的帮助!
答案 0 :(得分:2)
使用接口并将接口实例作为第二个枚举参数,或者为其提供在实例中实现的抽象方法。例如:
enum MyEnum {
ONE("first", new MyInterface() {
@Override
public void commonMethod() {
System.out.println("First!");
}
}) {
@Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, first!");
}
},
TWO("second", new MyInterface() {
@Override
public void commonMethod() {
System.out.println("Second!");
}
}) {
@Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, second!");
}
},
THREE("last", new MyInterface() {
@Override
public void commonMethod() {
System.out.println("Third!");
}
}) {
@Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, third!");
}
};
private String message;
private MyInterface myType;
private MyEnum(String m, MyInterface myType) {
message = m;
this.myType = myType;
}
public String getMessage() {
return message;
}
public MyInterface getMyType() {
return myType;
}
public void enumMethod() {
System.out.println(message);
}
public abstract void abstractEnumMethod();
}
interface MyInterface {
void commonMethod();
}
答案 1 :(得分:0)
答案全部取决于你想要实现的目标。例如,您可以在enum
内提供一个通用方法,并检查调用它的枚举实例...
public class TestEnum {
public static void main(String[] args) {
MyEnum.ONE.doStuff();
MyEnum.TWO.doStuff();
MyEnum.THREE.doStuff();
}
public enum MyEnum {
ONE("first"),
TWO("second"),
THREE("last");
public String message;
MyEnum(String m) {
message = m;
}
public void doStuff() {
System.out.println(name());
if (ONE.equals(this)) {
System.out.println("...Do stuff for one");
} else if (TWO.equals(this)) {
System.out.println("...Do stuff for two");
} else if (THREE.equals(this)) {
System.out.println("...Do stuff for three");
}
}
}
}
哪些输出......
one
...Do stuff for one
two
...Do stuff for two
three
...Do stuff for three