1

I have written the following generic function in Java:

public <T extends MyClass> void loadProperties(String in_strPath)
{
   // ...
}

The type T can be any of 3 different classes which are children of MyClass. Let's call those 3 classes MyClassV1, MyClassV2 and MyClassV3. I would like to print the name of the class that corresponds to T from whithin loadProperties. I tried doing this:

Class<T> c = T.class;
T instance = c.newInstace();
System.out.println(instance.getClass().getName());

But it does not work. Thanks for any advice.

user3266738
  • 477
  • 2
  • 12

1 Answers1

0

T represents type parameter, which gets "type-erased", so neither newInstance nor getClass().getName() would produce the desired result.

There is an idiom that you need to follow in order to make this work - pass Class<T> as a regular parameter to your method.

public <T extends MyClass> void loadProperties(String in_strPath, Class<T> classArg) {
    ...
    T instance = classArg.newInstance();
    System.out.println(instance.getClass().getName());
}

The caller needs to pass MyClassV1.class, MyClassV2.class, or MyClassV3.class as the second parameter.

Now that you use classArg instead of T, the code works as expected.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523