java 泛型 编译报错

wangsufu77 2019-12-25 08:33:53
代码如下:
package com.nettyClazzTest;


public class App {
public static void main(String[] args) {
GenericTest nettyTest=new GenericTest();
Person p= nettyTest.add(Person.class);

}

}

class GenericTest<T>{
public T add(Class<T> calzz){
try {
return calzz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
};


}
class Person{}

这一行编译报错
Person p= nettyTest.add(Person.class);
什么原因啊? 大佬们 help

...全文
155 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_39936465 2019-12-26
  • 打赏
  • 举报
回复
引用 楼主 wangsufu77 的回复:
代码如下: 这一行编译报错 Person p= nettyTest.add(Person.class); 什么原因啊? 大佬们 help
因为你前面 申明的Person 后面 生成的是泛用性T 2个类型不匹配所以会报错,一种方法像楼上一样,还有一种就是强制匹配Person类 Person p = (Person) nettyTest.add(Person.class);
Valerie00 2019-12-25
  • 打赏
  • 举报
回复
GenericTest<Person> nettyTest=new GenericTest<>();
Person p= nettyTest.add(Person.class);


创建对象的时候你需要指定泛型的类GenericTest<Person>

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧