How to get the class of type variable in Java Generics

前端 未结 7 1440
北恋
北恋 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:06

    There is a way to get the runtime type of the type parameter by using Guava's TypeToken to capture it. The solution's disadvantage is that you have to create an anonymous subclass each time you need an instance of Container.

    class Container {
    
        TypeToken tokenOfContainedType = new TypeToken(getClass()) {};
    
        public Type getContainedType() {
            return tokenOfContainedType.getType();
        }
    }
    
    class TestCase {
    
        // note that containerTest is not a simple instance of Container,
        // an anonymous subclass is created
        private Container containerTest = new Container() {};
    
        @Test
        public void test() {
            Assert.assertEquals(String.class, containerTest.getContainedType());
        }
    }
    

    The key of this solution is described in tha JavaDoc of TypeToken's constructor used in the code above:

    Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.

提交回复
热议问题