So, the JDK compiler compiles the first version, but not the second, and the Eclipse compiler does not compile either of the two versions.
In terms of Java bytecode, the first version contains two different methods (after type erasure), namely public java.lang.Boolean test() and public java.lang.Double test() , which is absolutely true. The JDK compiler and the Eclipse compiler sometimes generate such methods when you override common methods, but then they are marked as synthetic bridge methods.
The second version will contain two methods with the same signature (after erasing the type), which is not allowed in Java bytecode. Therefore, the JDK compiler cannot create such a class file. I just edited a class file with a hex editor to create a class with such methods, and after starting the program I get this error:
Exception in thread "main" java.lang.ClassFormatError: Duplicate method name&signature in class file SameSignatureMethods at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: SameSignatureMethods. Program will exit.
The class I started with is as follows. I used String and Double because they have the same name length:
public class SameSignatureMethods { public <T extends String> String test() { return null; } public <T extends Double> Double test() { return null; } public static void main(String[] args) { System.out.println(new SameSignatureMethods().<Double>test()); } }
Then, using a hex editor, I replaced the signature of the first method with public <T extends String> Double test() in two places in the class file, one with the raw signature ()Ljava/lang/Double; , one with a common signature <T:Ljava/lang/String;>()Ljava/lang/Double; .
Christian semrau
source share