我有一个静态方法,该方法将根据类的类型返回自定义类型,
public class GenericMethod {
public static <T> T returnGeneric(Class<T> clazz) {
return null;
}
}
现在,我想向其中传递一个具有通用类型的类,
CustomType<String> type = GenericMethod.returnGeneric(CustomType.class);
唯一的问题是上述语句给出了未经检查的转换警告。
我尝试了new CustomType<String>().getName()
无法解决问题的解决方法。
是否有正确的方法,还是唯一的解决方法是使用@SuppressWarnings
?
您想/应该尝试的是:
CustomType<String> type = GenericMethod.returnGeneric(CustomType<String>.class);
不幸的是,由于类型擦除,CustomType<A>.class
and之间没有区别CustomType<B>.class
,因此Java不支持此语法。
因此,我的$ .02:无法实现您的要求,所以请继续使用@suppresswarnings ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句