> Hello. I was wondering if there is a better way to write the below
> code. I have several enums, where each enum is for an option type and
> each option has a short 1-3 letter string used when I need to identify
> the option from a string. The code for each option type is identical
> and I'd prefer to not repeat it over and over again.
>> Hello. I was wondering if there is a better way to write the below
>> code. I have several enums, where each enum is for an option type and
[quoted text clipped - 5 lines]
> you particularly (and it would bother me ;-) I suggest that you generate the
> enum classes automatically.
Yes. That's the option.
But a little improvement is also possible here with a single
implementation of the lookup logic, like in the following example:
public class Options {
public interface Option {
String getOptionString();
}
public static enum YesNoOption implements Option {
YES("yes"), NO("no");
private final String str;
private YesNoOption(String str) { this.str = str; }
public String getOptionString() { return str; }
public static YesNoOption getOption(String str) {
return forString(YesNoOption.class, str);
}
}
// ... other options ...
public static <T extends Enum<T> & Option> T forString(
Class<T> optionType, String str) {
for(T o : optionType.getEnumConstants())
if(o.getOptionString().equals(str))
return o;
return null;
}
}
piotr
EJP - 18 Nov 2006 00:40 GMT
> public static YesNoOption getOption(String str) {
for(YesNoOption o: YesNoOption.values())
if(o.str.equals(str))
return o;
return null;
} }
This method is redundant. Enum has a static valueOf() method with,
curiously enough, the same parameters and return type as the above. It
throws IllegalArgumentException instead of returning null.
daniel_nordlund_1982@hotmail.com - 18 Nov 2006 10:15 GMT
EJP skrev:
> > public static YesNoOption getOption(String str) {
> for(YesNoOption o: YesNoOption.values())
[quoted text clipped - 6 lines]
> curiously enough, the same parameters and return type as the above. It
> throws IllegalArgumentException instead of returning null.
The problem is that with valueOf I have to use the full enum
identifier:
ColorOption color = ColorOption.valueOf("GREEN");
But I need this method to look up an option given it's abbreviation:
ColorOption color = ColorOption.getOption("g");
Thank you Piotr for your improved code!
Daniel
仁者无敌 - 18 Nov 2006 09:37 GMT
> > daniel_nordlund_1...@hotmail.com wrote:
>
[quoted text clipped - 35 lines]
> return o;
> return null;
Very strong template code......
hard to understand,could you explain what the template trys to
describe by the way?
> }
>
> }piotr