java 模板参数,有没有办法在Java中查找模板(通用)参数的类型?

本文探讨了在Java中如何尝试使用泛型获取类型,并指出由于类型擦除,Java无法在运行时获取泛型参数的类型。作者提到了C#中的typeof操作符作为对比,说明其在泛型和具体类型上的便利性。虽然Java没有直接的等价功能,但提出了通过传入Class对象作为参数来实现类似功能的工作方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying to do something like this in Java:

public static T foo() {

return (T) bar(T);

}

public static Object bar(Class> klaz) {

return klaz.newInstance();

}

But the code doesn't compile since I can't substitute T for a Class>.

With a concrete class, I can call bar like:

bar(ConcreteClass.class);

But the same does not work for T. i.e. there's no such thing as T.class

In C#, typeof works for both concrete and template types. So, the call to bar would've been:

bar(typeof(T));

But I haven't been able to find anything similar in Java.

Am I missing something, or does Java not have a way of getting the type of a template parameter? And if Java doesn't have the facility, are there any workarounds?

解决方案

There's no way to get the type. Java's generics use type erasure so even java itself does not know what T is at runtime.

As for workarounds: you could define foo to take a parameter of type Class and then use that.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值