`
chourentang
  • 浏览: 56692 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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

    博客分类:
  • Java
 
阅读更多
出现错误的代码如下:
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;
	}
}

错误信息:Illegal class literal for the type parameter Module

解决方法:将类ModServiceFinderImpl<Module>后的泛型参数去掉

修改后的代码:
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.

注:对泛型的讲解可产考:http://www.infoq.com/cn/articles/cf-java-generics
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics