我有三个通用接口(interface)(其中两个之间的关系是相反的)并且想用递归方法处理它们:
public interface User<R extends Role<R,U>, U extends User<R,U>>
{
public R getRole();
public void setRole(R role);
}
public interface Role<R extends Role<R,U>,U extends User<R,U>>
{
public List<R> getRoles();
public void setRoles(List<R> roles);
public List<U> getUser() ;
public void setUser(List<U> user);
}
现在我想在我的 Worker
类中使用递归进行一些处理:
public <R extends Role<R,U>,U extends User<R,U>> void recursion(List<R> roles)
{
for(R role : roles)
{
recursion(role.getRoles());
}
}
我收到此错误,但我不知道为什么这不起作用或我该如何解决:
Bound mismatch: The generic method recursion(List<R>) of type Worker is not
applicable for the arguments (List<R>). The inferred type User<R,User<R,U>>
is not a valid substitute for the bounded parameter <U extends User<R,U>>
最佳答案
我修改了它,没有使用通用通配符 ?
,所以它可以编译。
剥离与问题无关的方法声明后:
public interface Role<R extends Role<R, U>, U extends User<R, U>> {
public List<Role<R, U>> getRoles(); // Change here to return type
}
public interface User<R extends Role<R, U>, U extends User<R, U>> { // No change
}
// Change to method parameter type
public static <R extends Role<R, U>, U extends User<R, U>> void recursion(List<Role<R, U>> roles) {
for (Role<R, U> role : roles) { // Change to element type
recursion(role.getRoles());
}
}
我希望这些更改仍然适合您的设计 - 如果它们不适合您,请告诉我,我会尽力满足您的要求。
呸!艰难的!
关于java - 使用递归和通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088981/