我真的很喜欢在编码时读取枚举的简单性。最近我遇到了一个任务,我需要接受一个关键字列表,每个关键字都会执行一个操作。
示例关键词:早餐、午餐、晚餐
所以我希望能够写出这样的东西:,String whatImGoingToMake = Keywords.BREAKFAST("banana").getPopularRecipe();
,这里的想法是得到流行的早餐食谱,以香蕉为原料。我想到了这一点,因为我认为使用反射应该能够工作。
问题是我无法调用getPopularRecipe(),因为它不是静态的,并且不允许用于内部类。
强制枚举做这样的事情并使用类是不常见的,我说的对吗?对于下一位程序员来说,最简单的实现是什么?
也许是因为这里太晚了,但我在这一点上很挣扎。
如果可能的话,我尽量避免使用一长串IF语句或switch语句。我只是不喜欢看到它们,并不惜一切代价避免它们。所以我不想写这样的东西:
if (param.equals("BREAKFAST") {
//lookup in breakfast db
} else if (param.equals("LUNCH") {
//you get the idea - I dont like this since it can go on forever if we start adding BRUNCH, SUPPER, SNACK
}
下面是我感兴趣的开始工作的枚举:
public enum MyUtil {
BREAKFAST {
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
},
LUNCH {
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
}
}
发布于 2012-12-22 04:20:31
如果我没理解错的话,您需要在枚举中有一个abstract
方法getPopularRecipe()
,并且所有的枚举实例都应该被覆盖。
示例:
public enum MyUtil {
BREAKFAST {
@Override
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
},
LUNCH {
@Override
public String getPopularRecipe(String ingredient) {
//do something with ingredient
return recipe;
}
}
public abstract String getPopularRecipe(String ingredient);
}
有关更多信息,请参阅此tutorial (阅读至末尾)。
发布于 2012-12-22 05:28:23
你把事情搞得太复杂了:
public enum Meal {
BREAKFAST("Bacon and eggs"),
LUNCH("Salad"),
DINNER("Steak and veg");
private final String ingredient;
Meal(String ingredient) {
// do whatever you like here
this.ingredient = ingredient;
}
public String getPopularRecipe() {
return ingredient;
}
}
构造函数、字段和方法可以和普通类一样复杂。枚举比许多人意识到的更类似于普通类。它们甚至不是不可变的(学究们注意到:虽然引用是最终的,但实例和任何类一样都是可变的-例如枚举可以有setter方法等)
https://stackoverflow.com/questions/14000009
复制相似问题