It's difficult to explain what I'm trying to achieve here (so...sorry if I missed a glaringly obvious answer in my searching)...
I'm trying to dynamically instantiate an object based on a Class paired to a value in a HashMap. However, I've been having issues finding an approach that actually works. Currently, I'm doing something like this:
HashMap<String, Flag<?>> flags = new HashMap<String, Flag<?>>();
HashMap<String, Class> keys = new HashMap<String, Class>();
keys.put("test", BooleanFlag.class);
keys.put("thing", StringFlag.class);
keys.put("foo", DoubleFlag.class);
for (Map.Entry<String, Class> key : keys.entrySet()) {
try {
Class c = key.getValue();
Object obj = c.getConstructor(String.class, String.class).newInstance(key.getKey(), "test value that will be checked and coerced by one of the flag classes");
flags.put(key.getKey(), c.cast(obj));
} catch (Exception ex) {
//exception handling
}
}
In this current incarnation of the method, c.cast(obj) throws a compiler error about an Object being found where Flag is expected. Am I going about this horribly wrong/is this possible?