有没有办法在Java中查找模板(通用)参数的类型? [英] Is there a way to find the type of a template (generic) parameter in Java?

查看:610
本文介绍了有没有办法在Java中查找模板(通用)参数的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static< T>< p> T foo(){
return(T)bar(T);


public static Object bar(Class<?> klaz){
return klaz.newInstance();
}

但是代码不能编译,因为我无法替换 T 用于 Class <?>

对于具体的类,我可以像 bar 那样调用:

  bar(ConcreteClass.class); 

但是对于 T 不起作用。即没有像T.class这样的东西在C#中,typeof 适用于具体类型和模板类型。所以,打电话给酒吧会是:

  bar(typeof(T)); 

但是我一直无法在Java中找到类似的东西。

我是否错过了某些东西,或者Java没有办法获得模板参数的类型?如果Java没有设施,是否有任何解决方法?

解决方案

无法获取类型。 Java的泛型使用类型擦除,所以即使java本身也不知道T在运行时是什么。



至于解决方法:您可以定义foo来获取 Class< T> 然后使用它。


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

public static <T> 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<T> and then use that.

这篇关于有没有办法在Java中查找模板(通用)参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆