Using getActualTypeArguments in a General Context

There are other related issues, for example. 6624113 , 3403909 , 4516891 , but my question is simpler and more specific.

I want to know at run time with which parameter my class was assigned: - I want a class object of type parameter type. Due to type erasure, the T.class expression T.class not work, and there is no typeof(T) type function in C # to get this function.

However, there is some "uber-reflection" available through ParameterizedType and related classes that I almost completely have.

 import java.lang.reflect.ParameterizedType; public class MyClass<T> { public static void main( String[] args ) { new MyClass<Integer>().printTypeParam(); } public void printTypeParam() { class DummyT extends MyClass<T> {} class DummyString extends MyClass<String> {} ParameterizedType ptT = ((ParameterizedType) DummyT.class.getGenericSuperclass() ); ParameterizedType ptString = ((ParameterizedType) DummyString.class.getGenericSuperclass() ); System.out.println( "DummyT: " + ptT + " " + ptT.getActualTypeArguments()[0] ); System.out.println( "DummyString: " + ptString + " " + ptString.getActualTypeArguments()[0] ); } } 

When I run above, I see this output:

 DummyT: MyClass<T> T DummyString: MyClass<java.lang.String> class java.lang.String 

As you can see, this works when type arguments are known at compile time in a line of code containing a call to getGenericSuperClass , but where this call itself deals with generics, it simply prints the type name.

Is it possible to get the first line to print java.lang.Integer instead of T ?

+6
source share
1 answer

You cannot, simple and simple. Integer not endorsed, fully erased . If you do not believe me, compile the file once with Integer and once with Long . Two binary class files will be exactly the same.

Erasing styles is a harsh reality that you cannot do without. I suggest you rethink why you need it, instead of following the path of introducing hacks to avoid this.

Useful AngelikaLanger Generics FAQs:

+3
source

Source: https://habr.com/ru/post/900788/


All Articles