I have a class
public abstract class FakeClass<T extends MyClass> {
protected HashMap<Character, T> myMap;
private void myMethod(){
myMap.put('c', /*???? I need to instatiate something of type T here.*/)
}
}
As you can see, I can’t figure out how to instantiate something of type T. Is this possible? If so can someone point me in the right direction to do it?
Thanks!
This can only be done by passing some information about T to
myMethod(). One approach, described in this thread, is to pass a factory object forT. A special case of this, described in this thread, is to pass aClass<T> typeargument tomyMethod(), which can then usetype.newInstance()to create a new T object using the default constructor. (This will fail if T does not have a default constructor.) TheClassobject serves as the factory object forT.The reason we need all this is due to type erasure in Java.