0

I've use this method to retrieve the type of my generic, and no problem... until now
Now, I've got this kind of structure:

public class Toto<T> extends OtherOne<X,Y,Z> {...}`

and when I use the

((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];`

it's return me the type Class<X> of my OtherOne class, not Class<T>!

Has anyone ever encountered this problem? Whatever I've tried didn't work, and I don't want to use this solution of getting the class as an argument of my Constructor.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
LE GALL Benoît
  • 7,159
  • 1
  • 36
  • 48

1 Answers1

-1

In order to learn what T is it will have to be captured in a subclass. Ex:

public class StringToto extends Toto<String> {}
Class<?> t = (Class<?>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];

This is the case since types are only retrievable at runtime if they're part of a type definition.

Jonathan
  • 5,027
  • 39
  • 48
  • it isn't what I ask, please read again : public class Toto extends OtherOne {...}. I got a generic class wich extends an other generic class – LE GALL Benoît Sep 18 '14 at 08:34
  • It's not clear what you're trying to achieve - are you trying to get the value of `T`? – Jonathan Sep 18 '14 at 21:29
  • Yes I need to get the Class of T, but on a class wich extends a class which have generics too, so the common ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; doesnt work ! – LE GALL Benoît Sep 19 '14 at 09:00
  • If you want to get `T`, the actual value of T (such as String) must be captured in a type definition, such as in the example I posted. Without being captured in a type definition, the value of `T` is erased at runtime. – Jonathan Sep 19 '14 at 15:57