How to get the class of type variable in Java Generics

前端 未结 7 1418
北恋
北恋 2021-02-01 17:24

I\'ve seen similar questions but they didnt help very much.

For instance I\'ve got this Generic Class:

public class ContainerTest
{

    public          


        
7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 18:27

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

    class MyStringClass extends ContainerTest {}
    

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

    ContainerTest myStringClass = new ContainerTest{}();
    

    Then to resolve the value of T, you can use TypeTools:

    Class stringType = TypeResolver.resolveRawArgument(ContainerTest.class, myStringClass.getClass());
    assert stringType == String.class;
    

提交回复
热议问题