Java: Why does the method type in the .class file contain the return type, and not just the signature?

There is a NameAndType structure in the constant pool in the .class file. It is used for dynamic binding. All methods that the class can "export" are described as "signature type + return". how

  "getVector () Ljava / util / Vector;" 

This breaks my code when the return type of a method in some .jar changes even if the new type is already.

i.e.: I have the following code:

  List l = some.getList (); 

External .jar contains:

  public List getList () 

How does an external jar change the method signature to

  public ArrayList getList (). 

And my code dies at runtime with NoSuchMethodException because it cannot find

  getList () Ljava / util / List; 

So, I need to recompile my code. I do not need to change it. Just recompile the exact same code!

It also makes it possible to have two methods with the same signature, but with different return types! The compiler did not agree with this, but this can be done using direct opcoding.

My questions are why? Why would they do that?

I have only one idea: to prevent complex type checking at runtime. You need to look at the hierarchy and check if there is a parent interface with the List interface. It takes time, and only it has a compiler. JVM does not.

I'm right?

thanks.

+4
source share
1 answer

One reason may be that method overload is determined at compile time (as opposed to overriding). Consider the following methods:

public void doSomething(List util) {} public void doSomething(ArrayList util) {} 

And consider the code:

 doSomething(getList()); 

If Java allows a change in the type of the return value and does not throw an exception, the called method will still be doSomething (List), until you recompile - then it will be doSomething (ArrayList). This would mean that the working code will change the behavior only in order to recompile it.

+2
source

All Articles