Reputation: 1651
I really like the ease of reading Enums while coding. Recently I came across a task where I need to accept a list of keywords and each would perform an action.
Example keywords: BREAKFAST, LUNCH, DINNER
So I would like to be able to write something like this:
String whatImGoingToMake = Keywords.BREAKFAST("banana").getPopularRecipe();
The idea here is to get the popular breakfast recipes with banana as an ingredient.
I thought of this since I figured using reflections it should be able to work.
The problem is I'm unable to call getPopularRecipe() since its not static, and not allowed for inner classes.
Am I correct, that its not common to force enums to do something like this and use classes instead? What's the simplest implementation for the next coder to come along and pick this up to understand?
Maybe because its late here, but I'm struggling at this point.
I'm trying to stay away from a long list of IF statements or switch statements if possible. I just don't like seeing them and avoid them at all cost. So I don't want to write something like:
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
}
Here is the enum that Im interested in getting to work:
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;
}
}
}
Upvotes: 0
Views: 137
Reputation: 425358
You are over complicating things:
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;
}
}
The constructor, fields and methods can be as complicated as those for normal classes. Enums are much more similar to normal classes than many realise. They are not even immutable (pedants note: while the references are final, the instances are as mutable as any class - eg enums could have setter methods etc)
Upvotes: 0
Reputation: 66667
If I understand your question correctly, you need to have a abstract
method getPopularRecipe()
in Enum and all enum instances should override.
Example:
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);
}
See this tutorial for more info (Read till end).
Upvotes: 3