0

In my program I have an abstract base class with a generic parameter. In this class I have to get the Class object of the generic parameter used in a subclass. Currently I do it like this:

public abstract class BaseItem<T>
    public BaseItem(int id, Class<T> childGenricClass) {
        //...
    }
}

public class MainItem extends BaseItem<String> {
    public MainItem(int id) {
        super(id, String.class);
    }
}

Do I really have to pass the class via the constructor to the parent class or is there a way in Java to dynamically get this from the parent class?

Cilenco
  • 6,951
  • 17
  • 72
  • 152

2 Answers2

1

This is correct, because JVM removeы all types at run-time. At run-time your T is always Object, so your application doesn't have any chanse to find out what class of T is. Therefore you have to additionally add Class<T> cls variable.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

You can so something like this (altough passing class is nicer imo) :

public abstract class BaseItem<T> {
    public BaseItem(int id) {}

    public Class<T> getGenericClass() {
        return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
}

new MainItem().getGenericClass(); // returns Class<String>