djs22
djs22

Reputation: 1156

Java Generics Question

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!

Upvotes: 1

Views: 219

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

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 for T. A special case of this, described in this thread, is to pass a Class<T> type argument to myMethod(), which can then use type.newInstance() to create a new T object using the default constructor. (This will fail if T does not have a default constructor.) The Class object serves as the factory object for T.

The reason we need all this is due to type erasure in Java.

Upvotes: 7

trutheality
trutheality

Reputation: 23455

Usually, the point of generics is to be able to accept an unknown-at-compile-time type as input.

You can't instantiate an unknown class (because it might not have a visible constructor). If you just need a placeholder to put into the map, you can put a null value.

Without knowing more context, there isn't much more that anyone can do.

Upvotes: 0

Related Questions