在Java 8中,如果我有两个具有不同(但兼容)返回类型的接口,则反射告诉我两个方法中的一个是默认方法,即使我实际上没有将该方法声明为默认方法或提供方法体.
例如,请使用以下代码段:
package com.company;
import java.lang.reflect.Method;
interface BarInterface {}
class Bar implements BarInterface {}
interface FooInterface {
public BarInterface getBar();
}
interface FooInterface2 extends FooInterface {
public Bar getBar();
}
class Foo implements FooInterface2 {
public Bar getBar(){
throw new UnsupportedOperationException();
}
}
public class Main {
public static void main(String[] args) {
for(Method m : FooInterface2.class.getMethods()){
System.out.println(m);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Java 1.8生成以下输出:
public abstract com.company.Bar com.company.FooInterface2.getBar()
public default com.company.BarInterface com.company.FooInterface2.getBar()
Run Code Online (Sandbox Code Playgroud)
这看起来很奇怪,不仅因为两种方法都存在,而且因为其中一种方法突然而且莫名其妙地变成了默认方法.
尽管两种方法具有相同的签名,但在Java 7中运行相同的代码会产生一些不太意外的情况,尽管仍然令人困惑:
public …Run Code Online (Sandbox Code Playgroud)