How to get the Generic Type Parameter?

我们两清 提交于 2019-12-04 14:11:49
barfuin

This is sort of difficult, because Java deliberately can't do that ("type erasure").

The work-around is called super type tokens. There are also some threads on SO about that (like this one or that one).

When you have a question like this, you should ask yourself, how would you do it without Generics? Because any Generics program can be converted into an equivalent program without Generics. (This conversion is called type erasure.) So if you cannot do it without Generics, you cannot do it with Generics either.

Your program without Generics looks like this:

public static class MyClass {
    ArrayList mArrayList = new ArrayList();
}

@Test
public final void test() {
    MyClass myObject = new MyClass();
    Integer result = getParamType( myObject ); // how would you implement getParamType()?
}

Java has a misguided feature called Type Erasure that specifically prevents you from doing that.

Generic parameter information does not exist at runtime.

Instead, you can manually accept a Class<T>.

To learn the value of T you'll need to capture it in a type definition by subclassing MyClass:

class MyStringClass extends MyClass<String> {}

You can also do this with an anonymous class if you want:

MyClass<String> myStringClass = new MyClass<String>{}();

To resolve the value of T, you can use TypeTools:

Class<?> stringType = TypeResolver.resolveRawArgument(MyClass.class, myStringClass.getClass());
assert stringType == String.class;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!