关于java反射获取泛型

public class Test<T> {
    private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) {};
    private final Type type = typeToken.getRawType();

    public void foo() {
        System.out.println(this.type);
    }

    public static void main(String[] args) {
        Test<Integer> test = new Test<Integer>() {};
        Test<Integer> test2 = new Test<Integer>();
        test.foo();// class java.lang.Integer
        test2.foo();//
    }
}

利用以上代码可以获取泛型类型,对于test与test2的输出不同有些困惑。以下为解答:

首先,当利用

Test<String> test2 = new Test<String>();

进行实例化的时候,java没有办法将String传过去。于是

private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) {};

就无法得知T的具体类型,因此只能输出T。

 

接着对于

  private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) {};

根据javadoc(见参考链接2)

Constructs a new type token of T while resolving free type variables in the context of declaringClass.

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.

只有创建匿名子类,才能将类型参数嵌入到匿名子类的结构中,此时就能获取到Integer了(关于匿名子类如何操作,见参考链接3)

 

参考1:https://stackoverflow.com/questions/38046880/how-to-use-typetoken-to-get-type-parameter

参考2:https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/reflect/TypeToken.html#TypeToken(java.lang.Class)

参考3:http://gafter.blogspot.com/2006/12/super-type-tokens.html

转载于:https://www.cnblogs.com/ssklo/p/7068838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值