Get type name for generic parameter of generic cla

2020-01-29 05:10发布

I have a small problem in java while using genericity. I have a class A :

public class A<T>

In a method of A, I need to get the type name of T. Is there a way to find the string s using T ?

(If I create A<String> temp = new A<String>();, I want to be able to get java.lang.String at one point - I have to use genericity because one of my methods will have to return a List<T>).

This seems quite easy but I do not see how to do it.

标签: java generics
7条回答
Anthone
2楼-- · 2020-01-29 06:05

If you're doing it in a subclass which has it's parent class defining the generic type, this is what worked for me:

// get generic type class name
String name = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].toString();

// then when you've got the name, you can make the Class<T> object
Class.forName(name.replace("class ", ""))

Reason why I couldn't do it with #getClass() instead of #toString() in the first snip is that I was always getting the "Class" class, which is useless to me.

查看更多
登录 后发表回答