0

I have an abstract class:

abstract class DmValue<T>

And many classes extends it, for example:

class DmBoolean extends DmValue<Boolean>

class DmText extends DmValue<String>

class DmDate extends DmValue<Date>

My question is how to find T class?

I need to write a static function:

static Class getT(Class<? extends DmValue> valueClass){...}

In case of valueClass = DmText.class, getT function should return String.class

In case of valueClass = DmBoolean.class, getT function should return Boolean.class

Any suggestions?

Ofir
  • 43
  • 5
  • The type in Java is a construct that only exists up to the compile time and is not available in the executable/byte code. Thus it is impossible to determine a Class object at runtime. – Ray Apr 15 '17 at 19:07
  • make Class a field and pass the concrete class to the abstract's constructor? – mre Apr 15 '17 at 19:07

2 Answers2

1

Pass Class<T> in your constructors,

abstract class DmValue<T> {
    Class<T> cls;
    public DmValue(Class<T> cls) {
        this.cls = cls;
    }
    public Class<T> getValueType() {
        return this.cls;
    }
}

Then initialize it in your subclasses, like

class DmBoolean extends DmValue<Boolean> {
    public DmBoolean() {
        super(Boolean.class);
    }
}

Then you can access it by calling getValueType().

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
You can grab generic interfaces of a class by Class#getGenericInterfaces() which you then in turn check if it's a ParameterizedType and then grab the actual type arguments accordingly.

Type[] genericInterfaces = BarFoo.class.getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
    if (genericInterface instanceof ParameterizedType) {
        Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
        for (Type genericType : genericTypes) {
            System.out.println("Generic type: " + genericType);
        }
    }
}
strash
  • 1,291
  • 2
  • 15
  • 29