I have a class Foo<T, U> with the following constructor:
public Foo() {
clazz = Class<U>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
What I do in the constructor is getting the class of the argument U. I need it because I use it for instantiating that class.
The problem is that it doesn't work when I have a subclass of Foo that isn't a direct sublcass of it. Let me put it with an example.
I have the class Bar<T> extends Foo<T, Class1>. Here, Class1 is not a variable but a class.
I also have the class Baz extends Bar<Class2>. Class2 is a class too, not a variable.
The problem is that it fails when I try to instantiate Baz (Baz -> Bar<Class2> -> Foo<T, Class2>). I get an ArrayIndexOutOfBoundsException because getActualTypeArguments() returns an array containing only the class Class2 (size 1) and I'm trying to get the second element of the array. That's because I'm getting the arguments of Bar<Class2>, instead of the ones of Foo.
What I want is to modify the Foo constructor some way I can get the class in the paramter U, doesn't matter if the class I instantiate is a direct subclass or not. I think I should can go up in the hierarchy of classes until reach the class Foo, cast it as ParameterizedType and get the arguments, but I couldn't find how.
Any idea?
Thanks in advance.