[英]java extending Generic types ambiguous method call
I have run into a problem which is hard for me to understand why this happens. 我遇到了一个问题,我很难理解为什么会这样。
I have a generic class B which extends generic class A and i have two methods accepting A and B. From method accepting A i want to call method with paramter B but this results in compilation error: 我有一个泛型类B,它扩展了泛型类A,并且我有两个接受A和B的方法。从接受A的方法中,我想用参数B调用方法,但这会导致编译错误:
Ambiguous method call. 方法调用不明确。 Both method (A) in Main and method (B) in Main match Main中的方法(A)和Main中的方法(B)
Here is a code snippet: 这是一个代码片段:
public class Main {
private static class A<T> {
}
private static class B<T> extends A {
}
public String method(A<String> arg) {
return method((B<String>) arg));
}
public String method(B<String> arg) {
return "some result";
}
}
However if I remove generic type from type A it compiles: 但是,如果我从类型A中删除泛型类型,则会进行编译:
public class Main {
private static class A<T> {
}
private static class B<T> extends A {
}
public String method(A arg) {
return method((B<String>) arg));
}
public String method(B<String> arg) {
return "some result";
}
}
What is the reason of that ? 是什么原因呢?
Edit: This issue is somehow related to java 8 because this code is compilable with JDK7 编辑:此问题某种程度上与Java 8有关,因为此代码可与JDK7一起编译
Your class B
extends A
but it's not specifying its bounds nor any generic info 您的B
类扩展了A
但没有指定范围,也没有任何一般信息
What I mean is that your line 我的意思是你的台词
private static class B<T> extends A { ... }
is equivalent to 相当于
private static class B<T> extends A<Object> { ... }
By changing it to 通过将其更改为
private static class B<T> extends A<T> { ... }
Your code will compile 您的代码将编译
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.