所以,我有public interface NodeLevel<E extends NodeLevelEnum>
,它有方法public E getParent()
和public E getEnum()
。实现abstract public class NodeLevelAbstract<E extends NodeLevelEnum> implements NodeLevel<E>
委托给实现A
的类public interface NodeLevelEnum<E extends NodeLevelEnum>
的实例。最后一个声明应该意味着实现NodeLevelEnum
的类的实例可以对实现NodeLevelEnum
的类的实例执行某些操作。
现在,这是NodeLevelAbstract#getParent()
:
@Override
public E getParent() {
return this.getEnum().getParent();
}
导致编译器错误(我使用NetBeans 7.2,顺便说一句):
incompatible types
required: E
found: NodeLevelEnum
where E is a type-variable:
E extends NodeLevelEnum declared in class NodeLevelAbstract
对我而言,这意味着需要NodeLevelEnum
的后代,但找到NodeLevelEnum
,考虑到Java Generics中的绑定本身,它听起来就像绝对的bollocks。
为什么这些类型不兼容?是否有任何优雅的方式来做我的意思? 提前致谢。 =)
更新1
顺便说一下,NodeLevelEnum#getParent()
返回<E extends NodeLevelEnum>
,而不是NodeLevelEnum
,错误说明了这一点。
更新2
abstract public class NodeLevelAbstract<E extends NodeLevelEnum> implements
NodeLevel<E> {
protected E _enum;
@Override
public E getEnum() {
return this._enum;
}
@Override
public E getParent() {
return this.getEnum().getParent();
}
public static <E extends NodeLevelEnum<E>> E[] getEnumLineage(E _enum) {
ArrayList<E> ancestors = new ArrayList<>();
E currentEnum = _enum;
do {
ancestors.add(currentEnum);
currentEnum = currentEnum.getParent();
} while (currentEnum != null);
return (E[]) ancestors.toArray();
}
public static <E extends NodeLevelEnum<E>> HashMap<String, String>
getEnumLineageValueMap(
E _enum) {
HashMap<String, String> map = new HashMap<>();
for (E e : getEnumLineage(_enum)) {
map.put(e.getCode(), e.getValue());
}
return map;
}
}
public interface NodeLevel<E extends NodeLevelEnum> {
public E getEnum();
public E getParent();
}
public interface NodeLevelEnum<E extends NodeLevelEnum> {
public E getParent();
}
public interface FilestructureLevel<E extends NodeLevelEnum<E>> extends
NodeLevel<E> {
public String getPathPrefix();
}
public class FileLevel<E extends NodeLevelEnum<E>> extends NodeLevelAbstract<E>
implements FilestructureLevel<E> {
protected String _pathPrefix;
@Override
public String getPathPrefix() {
return this._pathPrefix;
}
public HashMap<String, String> getValueMap(Boolean withPath) {
return getEnumLineageValueMap(this.getEnum(), withPath);
}
public static <E extends NodeLevelEnum<E>> HashMap<String, String>
getEnumLineageValueMap(
E _enum) {
return getEnumLineageValueMap(_enum, false);
}
public static <E extends NodeLevelEnum<E>> HashMap<String, String>
getEnumLineageValueMap(
E _enum, Boolean withPath) {
HashMap<String, String> map = new HashMap<>();
FileLevelEnum[] lineage = (FileLevelEnum[]) getEnumLineage(_enum);
for (FileLevelEnum e : lineage) {
String value = !withPath ? e.getValue() : e.getPathPrefix()
+ e.getValue();
map.put(e.getCode(), value);
}
return map;
}
}