考虑以下两个方法定义:
static <T extends Do & Done>T whatToDo(T ele){return null;}
static <R extends Done & Do>R whatToDo(R ele){return null;}
两者都将分别具有以下擦除:
static Do whatToDo(Do);
static Done whatToDo(Done);
考虑具体的类和Doing
接口Do
Done
interface Do{void doIt();}
interface Done{void didIt();}
class Doing implements Do,Done{
@Override
public void doIt() {}
@Override
public void didIt() {
}
}
现在,当我尝试调用 methodwhatToDo
时,即使方法在类中正确编译,也会出现模棱两可的调用编译错误。仅在调用时,我收到错误。
public static void main(String[] args) {
whatToDo(new Doing()); //compile error : ambiguous method call
}
这是否意味着擦除的定义对异常负责,只有最左边的元素被视为给定有界类型的擦除?另外,为什么选择擦除是这种方式?JLS 定义擦除过程的方式是否有更好的方法?
理想的情况是Java不应该通过修改擦除的定义以包括无序的边界集而不是最左边的边界来允许在这种情况下存在这两种方法?
这是完整的代码:
class Scratch {
public static void main(String[] args) {
whatToDo(new Doing());
//Compilation error : because of Erasure - the 2 definitions exist even though the
//the elements of the bounds are exactly the same
//Ideally this should have been unordered list of bounds rather than left most bound?
}
static <T extends Do & Done>T whatToDo(T ele){return null;}
static <R extends Done & Do>R whatToDo(R ele){return null;}
}
interface Do{void doIt();}
interface Done{void didIt();}
class Doing implements Do,Done{
@Override
public void doIt() {}
@Override
public void didIt() {
}
}