4

I'm trying to make a new Object of type T.

I tried:

T h = new T();
T h = T.newInstance();

Those don't work. I also tried:

T h = (T)(new Object());

That works, but then h.getClass().getName() returns java.lang.Object

Is there any way to make a default object of this class without knowing the class name?

EDIT (from comments):

T is a generic. Like Class<T>.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
PitaJ
  • 12,969
  • 6
  • 36
  • 55

3 Answers3

5

As Jon commented you explictly need the class due to type erasure.

E.g. if you have a generic method, you'll have to do it like this:

public void <T> myMethod(Class<T> clazz) {
    T foo = clazz.newInstance();
}

If it's a generic class it basically works the same. You just have to pass the class object to the metod or even to the constructor.

André Stannek
  • 7,773
  • 31
  • 52
0

You can also use the Prototype Pattern

public E makeNew(E template) throws IllegalAccessException,InstantiationException{
    E newobject=(E)template.getClass().newInstance();
    return newobject;
}
HowYaDoing
  • 820
  • 2
  • 7
  • 15
0

You can only create instances of known types. T is not something that comes with Java, but it is often used as an internal type parameter in a class that takes a type parameter (java generics).

As an example, say that you are creating a type parameterized linked list, that is, a linked list that you can use with any one data type as contents. If you would want an instance of this class that could only contain Strings, you would instantiate it like so:

MyLinkedList<String> list = new MyLinkedList<String>();

The definition of such a class needs a type parameter, that will represent whatever class it was instantiated with, and would look something like this:

class MyLinkedList<T> {
    // implementation code
} 

Inside that class, you can create instances of type T, and you would do it with T t = new T();, just like you'd expect. T will however refer to some other class at runtime, since T is just a type parameter.

That T type will however not be accessible outside the class.

If you're not implementing a type parameterized class, you would have to create a class of type T in order to instantiate it, and make sure to include it into whatever scope you want to use it in. I wouldn't recommend doing that though, because it Isn't very descriptive.

Frost
  • 11,121
  • 3
  • 37
  • 44