我试图创建一种构建"嵌套"的方法。路径对象。我想要的是这样的
public Path<?> getPath(Path<?>path, SingularAttribute<?, ?>attribute) {
return path.get(attribute);
}
但是我收到以下错误:
error: no suitable method found for get(SingularAttribute<CAP#1,CAP#2>)
return path.get(attribute);
method Path.<Y#1>get(SingularAttribute<? super CAP#3,Y#1>) is not applicable
(cannot infer type-variable(s) Y#1
(argument mismatch; SingularAttribute<CAP#1,CAP#2> cannot be converted to SingularAttribute<? super CAP#3,Y#1>))
method Path.<E,C>get(PluralAttribute<CAP#3,C,E>) is not applicable
(cannot infer type-variable(s) E,C
(argument mismatch; SingularAttribute<CAP#1,CAP#2> cannot be converted to PluralAttribute<CAP#3,C,E>))
method Path.<K,V,M>get(MapAttribute<CAP#3,K,V>) is not applicable
(cannot infer type-variable(s) K,V,M
(argument mismatch; SingularAttribute<CAP#1,CAP#2> cannot be converted to MapAttribute<CAP#3,K,V>))
method Path.<Y#2>get(String) is not applicable
(cannot infer type-variable(s) Y#2
(argument mismatch; SingularAttribute<CAP#1,CAP#2> cannot be converted to String))
where Y#1,X,E,C,K,V,M,Y#2 are type-variables:
Y#1 extends Object declared in method <Y#1>get(SingularAttribute<? super X,Y#1>)
X extends Object declared in interface Path
E extends Object declared in method <E,C>get(PluralAttribute<X,C,E>)
C extends Collection<E> declared in method <E,C>get(PluralAttribute<X,C,E>)
K extends Object declared in method <K,V,M>get(MapAttribute<X,K,V>)
V extends Object declared in method <K,V,M>get(MapAttribute<X,K,V>)
M extends Map<K,V> declared in method <K,V,M>get(MapAttribute<X,K,V>)
Y#2 extends Object declared in method <Y#2>get(String)
where CAP#1,CAP#2,CAP#3 are fresh type-variables:
CAP#1 extends Object from capture of ?
CAP#2 extends Object from capture of ?
CAP#3 extends Object from capture of ?
有关如何解决此错误的任何建议吗?非常感谢。
更新我找到了使用辅助方法的快速解决方法:
public Path<?> getPath(Path<?> path, SingularAttribute<?, ?> attribute) {
return getPathHelper(path, attribute);
}
@SuppressWarnings("unchecked")
private <X, Y> Path<Y> getPathHelper(Path<X>, SingularAttribute<?, ?> attribute) {
return path.get((SingularAttribute<? super X, Y>) attribute);
}
这可以,但这段代码是正确的吗?
答案 0 :(得分:0)
您可以使用
public <X, Y> Path<Y> getPath(Path<X> path, SingularAttribute<? super X, Y> attribute) {
return path.get(attribute);
}
此方法签名比以前更具限制性,因此您必须检查它是否适用于您的情况。
编写它是为了匹配Path.get
方法的返回类型。
希望这有帮助。