java泛型类层次结构和泛型实现

Rit*_*esh 3 java generics

这可能是一个愚蠢的问题,但我无法理解为什么下面的编译失败了.

我的班级层次结构

Dao.java

public interface Dao<E extends Entity, S extends SearchCriteria> {
    <E> E create(E e) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

这个Dao有一个通用的实现

DaoImpl.java

public abstract class DaoImpl<E extends Entity, S extends SearchCriteria> implements Dao<E, S> {
    @Override
    public <E> E create(E e) throws Exception {
        throw new UnsupportedOperationException("this operation is not supported");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后有专门的实施

ProcessDaoImpl.java

public class ProcessDaoImpl extends DaoImpl<Process, WildcardSearchCriteria> {
    @Override // this is where compilation is failing, I get the error that create doesn't override a superclass method
    public Process create(Process entity) throws Exception {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

实体类层次结构的描述

Process.java

public class Process extends AuditEntity {
    // some pojo fields
}

AuditEntity.java

public abstract class AuditEntity extends IdentifiableEntity {
    // some pojo fields
}

IdentifiableEntity.java

public abstract class IdentifiableEntity extends Entity {
    // some pojo fields
}

Entity.java

public abstract class Entity implements Serializable {
}
Run Code Online (Sandbox Code Playgroud)

dav*_*xxx 5

因为你应该在接口和抽象类中声明,所以 E create(E e)方法没有<E>在开头,否则你不会引用E类中声明的类型,而是引用E在方法范围内定义的类型:

替换:

 public interface Dao<E extends Entity, S extends SearchCriteria> {
    <E> E create(E e) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

通过

public interface Dao<E extends Entity, S extends SearchCriteria> {
     E create(E e) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

并取代:

@Override
public <E> E create(E e) throws Exception {
    throw new UnsupportedOperationException("this operation is not supported");
}
Run Code Online (Sandbox Code Playgroud)

通过:

@Override
public E create(E e) throws Exception {
    throw new UnsupportedOperationException("this operation is not supported");
}
Run Code Online (Sandbox Code Playgroud)