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

阅读更多
出现错误的代码如下:
public class ModServiceFinderImpl extends BaseFinderImpl implements ModServiceFinder{
	public PageView findByModid(String modid, int pageNo, int pageSize ) {
		PageView pv = new PageView();
		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后的泛型参数去掉

修改后的代码:
public class ModServiceFinderImpl extends BaseFinderImpl implements ModServiceFinder{
	public PageView findByModid(String modid, int pageNo, int pageSize ) {
		PageView pv = new PageView();
		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 {
  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 {

    private final Class clazz;

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

    protected MyGenericClass(Class 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

你可能感兴趣的:(Illegal class literal for the type parameter T错误解决方法)