Java – class #getdeclaredmethods () returns inherited methods
See English answers > getdeclaraedmethods() being differently in Java 7 vs. Java 81
interface A { A setX(Object x); A setY(Object y); } interface B extends A { B setX(Object x); }
If you try to put b.class Getdeclaredmethods() is used with jdk8 to get the next method:
Public abstractions b.setx (Java. Lang. object) and public default a b.setx (Java. Lang. object)
Javadoc says that class #getdeclaredmethods () only returns the declared method, so why do you return two methods? If someone has an explanation, why does the second method have a 'default' modifier?
Should I publish a bug report? This problem is very close to to this one, but the affected version is JDK6. For JDK7, it works normally (returns a single method)
Solution
I wouldn't say it was a mistake When your b interface is compiled by javac, it adds a synthetic bridge method that returns a You can see this by checking the javap output:
$javap -c B Compiled from "B.java" interface B extends A { public abstract B setX(java.lang.Object); public A setX(java.lang.Object); Code: 0: aload_0 1: aload_1 2: invokeinterface #1,2 // InterfaceMethod setX:(Ljava/lang/Object;)LB; 7: areturn }
In Java 1.7, of course, there is no such method, because it is impossible to create a default method in Java Therefore, when compiling in 1.7, you have the following:
$javap -c B Compiled from "B.java" interface B extends A { public abstract B setX(java.lang.Object); }
But in Java 1.8, this additional method is actually declared in bytecode, so getdeclaraedmethods () returns it correctly For this extra method, isbridge () and issynthetic () calls will return true, so if you don't like it, you can filter it according to it
Bridging methods are useful for correctly implementing covariant return types because the JVM does not understand this function They are required to dispatch virtual calls to methods with covariant return types The new bridging method in Java 1.8 helps to support the covariant return type of the default method The sub interface can define the default implementation of setx. In this case, an automatically generated bridge method is required to correctly dispatch calls to the implementation