Java 类型信息 —— 获取泛型类型的类对象(.class)

How to get a class instance of generics type T

考虑泛型类Foo<T>,在其成员中,如果想获取类型(type)T的类实例(class instance of type T),是不可以直接调用 T.class的。原因在于,Java 语言无法获取泛型类型参数(T)的运行时信息(不可以直接调用 T.class)。

  • 获得类名(以 String 的类型)

    public class A{}
    A.class.getSimpleName();
    

0. 常用解决方案

既然无法调用泛型类型参数的运行时类型信息,便在调用端,显示地传递该类的运行时类型信息进去(通过构造函数),一种惯用的解决方案如下:

class Foo<T> {
	private final Class<T> type;
	public Foo<T>(Class<T> type) {
		this.type = type;
	}
	public static void main(String[] args) {
		// 在客户端调用时,便会显得有些啰嗦
		Foo<SomeClass> f = new Foo<SomeClass>(SomeClass.class);
	}
}

1. Pure Java solution

  • <a href=“http://blog.xebia.com/acessing-generic-types-at-runtime-in-java/”, target="_blank">Accessing generic types at runtime in Java
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值