public abstract class BaseDaoImpl<E extends AbstractEntity> implements BaseDao<E> {
.....
public BaseDaoImpl() throws DataAccessException {
logger = LoggerFactory.getLogger(E); <<-- error here.
}
在上面的代码中,我在调用getLogger(E)
时收到错误。
E无法解析为变量
这是有道理的,但getLogger(E.class)
(或其变体)也不起作用。
我不想在构造函数中传递文字类,因此需要将构造函数标题更改为:
public BaseDaoImpl(Class<E> clazz) ...
不是一种选择。
如何从E
获取课程类型?
请注意以下答案:How to get class of generic type when there is no parameter of it?
没有帮助。
答案 0 :(得分:4)
在不更改构造函数的情况下,您无法在运行时学习任何有关静态不知道的E
。那是因为在Java中,通用参数没有任何运行时效果 - 编译器会逐字删除它生成的代码中对E
的所有引用。因此,如果您想要能够告诉其类型参数被实例化的类的代码,您必须自己添加某种参数(例如Class
对象)。没有办法解决它。
答案 1 :(得分:2)
有可能通过@CorayThan指出的反思。一种简单的方法是从方法签名
interface BaseDao<E>
E find(long id);
class FooDao implements BaseDao<Foo>
Foo find(long id)
所以可以通过
找到E类型this.getClass().getDeclaredMethod("find", long.class).getReturnType();
但是, 是在构造函数中传递Class
的一个非常好的选择。因为构造函数不是由用户代码调用的,所以详细程度不是问题。
abstract class BaseDaoImpl<E>
BaseDaoImpl(Class<E> clazz)
class FooDao extends BaseBaoImpl<Foo>
FooDao()
super(Foo.class);
// usages:
BaseDao<Foo> fooDao = new FooDao(); // clean & simple API
答案 2 :(得分:0)
由于泛型是使用类型擦除在Java语言中实现的,因此您无法执行任何需要运行时类型信息的操作。有关详细信息,请参阅this page。
答案 3 :(得分:-1)