Illegal class literal for the type parameter T错误解决方法

本文解决了一个关于Java泛型编程中出现的“非法泛型类字面量”错误。通过去除泛型参数并传递具体类型作为参数的方法绕过了这一限制,确保了程序的正确运行。

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

出现错误的代码如下:
public class ModServiceFinderImpl<Module> extends BaseFinderImpl<Module> implements ModServiceFinder<Module>{
public PageView<Module> findByModid(String modid, int pageNo, int pageSize ) {
PageView<Module> pv = new PageView<Module>();
if(modid != null && !"".equals(modid)) {
pv = super.findByPage(Module.class,
"from Module m where m.isShow=1 and m.parent.mod_id=" + modid, pageNo, pageSize);
}else {
pv = super.findByPage(Module.class, "from Module m where m.isShow=1",
pageNo, pageSize);
}
return pv;
}
}

[color=red]错误信息:Illegal class literal for the type parameter Module[/color]

[color=red]解决方法:将类ModServiceFinderImpl<Module>后的泛型参数去掉[/color]

修改后的代码:
public class ModServiceFinderImpl extends BaseFinderImpl<Module> implements ModServiceFinder<Module>{
public PageView<Module> findByModid(String modid, int pageNo, int pageSize ) {
PageView<Module> pv = new PageView<Module>();
if(modid != null && !"".equals(modid)) {
pv = super.findByPage(Module.class,
"from Module m where m.isShow=1 and m.parent.mod_id=" + modid, pageNo, pageSize);
}else {
pv = super.findByPage(Module.class, "from Module m where m.isShow=1",
pageNo, pageSize);
}
return pv;
}
}


总结:这个问题与网络上得另一个问题相同:
问题:Hi all,
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.
Example:
public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}

Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.
My question is: does someone know a good alternative or workaround for this?

解决方法:
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
public class MyGenericClass<T> {

private final Class<T> clazz;

public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
return new MyGenericClass<U>(clazz);
}

protected MyGenericClass(Class<T> clazz) {
this.clazz = clazz;
}

public void doSomething() {
T instance = clazz.newInstance();
}
}

It's ugly, but it works.

注:对泛型的讲解可产考:[url]http://www.infoq.com/cn/articles/cf-java-generics[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值