【发布时间】:2021-01-28 12:33:23
【问题描述】:
我注意到以下程序在使用 Java 8 和 Java 9 运行时的输出有所不同。
import java.lang.reflect.Method;
public class OrderingTest {
public static void main(String[] args) {
ServiceImpl service = new ServiceImpl();
for (Method method : service.getClass().getMethods()) {
for (Class<?> anInterface : method.getDeclaringClass().getInterfaces()) {
try {
Method intfMethod = anInterface.getMethod(method.getName(), method.getParameterTypes());
System.out.println("intfMethod = " + intfMethod);
} catch (NoSuchMethodException e) { }
}
}
}
}
class ServiceImpl implements ServiceX {
@Override
public Foo getType() { return null; }
}
interface ServiceX extends ServiceA<Foo>, ServiceB { }
abstract class Goo { }
class Foo extends Goo { }
interface ServiceA<S> {
S getType();
}
interface ServiceB {
@java.lang.Deprecated
Goo getType();
}
您可以在此处运行两个版本的 java: https://www.jdoodle.com/online-java-compiler/
Java 8 输出:
intfMethod = public abstract java.lang.Object ServiceA.getType()
intfMethod = public abstract java.lang.Object ServiceA.getType()
intfMethod = public abstract java.lang.Object ServiceA.getType()
Java 9 输出:
intfMethod = public abstract Goo ServiceB.getType()
intfMethod = public abstract Goo ServiceB.getType()
intfMethod = public abstract Goo ServiceB.getType()
但是当我将超级接口重新排序为:
interface ServiceX extends ServiceB, ServiceA<Foo> { }
然后两个版本的java输出:
intfMethod = public abstract Goo ServiceB.getType()
intfMethod = public abstract Goo ServiceB.getType()
intfMethod = public abstract Goo ServiceB.getType()
我想知道是什么原因造成的?是否有我不知道的新 Java 功能?
Java 8 文档 https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8
Java 9 文档 https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.8
【问题讨论】:
标签: java reflection java-8 overriding java-11