How can I use Java8 Supplier interface to rewrite this factory method to provide the proper typed instance?
I've a simple interface that extends Map:
public interface Thingy<K, V> extends Map<K, V> {}
Then I have a ThingyFactory class, which contains a list of all of the implementation classnames of Thingy:
public final class ThingyFactory {
Map<String, Class<Thingy<?, ?>>> thingyclasses = new ConcurrentHashMap<>();
.....
@SuppressWarnings("unchecked")
public <K, V> Thingy<K, V> getInstance(String classname) throws ThingyException {
Thingy<K, V> thingy;
try {
thingy = (Thingy<K, V>) thingyclasses.get(classname).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ThingyException("Something bad happened: ", e.toString());
}
return thingy;
}
}
I'm pretty sure that I can do this elegantly and w/o the SuppressWarnings and classloader using the Supplier interface but I can't seem to get the pattern quite right. Any guidance appreciated!