Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is method name/signature resolution done statically (compile-time)?

I encountered an interesting problem today which I thought was not possible in Java. I compiled my java code against version 2.6 of jgroups but used version 2.12 at runtime (tomcat web app deployment). I got the following error

org.jgroups.Message.<init>(Lorg/jgroups/Address;Lorg/jgroups/Address;Ljava/io/Serializable;)

Assuming that the API would have change since then, I thought of porting my code to jgroups-2.12, but to my surprise the code compiled fine with jgroups-2.12 and when I replaced the new jar (without changing a single line in my code, just compiling against jgroups-2.12 instead of jgroups-2.6), it worked perfectly fine.

I later realized that the constructor Message(Address, Address, Serializable) in 2.6 was changed to Message(Address, Address, Object) in 2.12. This means at runtime, the JVM was trying to locate the exact same method and was failing to do so.

Does this mean that Java compiler embeds the exact method name and precise arguments while compiling and a method with broader arguments won't work?

like image 329
Ashish Avatar asked Jan 17 '23 12:01

Ashish


1 Answers

Yes, that's exactly right - the exact signature is bound at compile-time, and that's what gets included in the bytecode.

In fact, this even includes the return type, which isn't included in signatures for things like overloading purposes.

Fundamentally, if you change anything about an existing public API member, that will be a breaking change. You can get away with some language-only changes, such as changing a String[] parameter to a String... parameter, or introducing generics (in some cases, if the erasure is compatible with the previous code), but that's pretty much it.

Chapter 13 of the Java Language Specification is all about binary compatibility - read that for more information. But in particular, from section 13.4.14:

Changing the name of a formal parameter of a method or constructor does not impact pre-existing binaries. Changing the name of a method, the type of a formal parameter to a method or constructor, or adding a parameter to or deleting a parameter from a method or constructor declaration creates a method or constructor with a new signature, and has the combined effect of deleting the method or constructor with the old signature and adding a method or constructor with the new signature (see §13.4.12).

like image 140
Jon Skeet Avatar answered Jan 20 '23 16:01

Jon Skeet