Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8022095

Clarify Object methods in 'interface' invocation mode

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 8
    • None
    • specification
    • None
    • Verified

      Given a variable i whose declared type is interface Foo, what will "i.hashCode()" compile to?

      Per 15.12.3, the most specific method is the hashCode method of interface Foo, which is implicitly declared to exist by 9.2. Then, per 15.12.3, the qualifying type of the invocation is Foo and the invocation mode is 'interface'. One would expect javac to emit an 'invokeinterface' instruction that references a CONSTANT_InterfaceMethodref_info structure for 'Foo.hashCode:()I'.

      In fact, javac in JDK7 and JDK8 emits an 'invokevirtual' instruction that references a CONSTANT_Methodref_info structure for 'java/lang/Object.hashCode:()I'. It is as if the qualifying type was Object and the invocation mode was 'virtual'.

      There is no problem at run time; the symbolic reference constructed from the constant pool will always resolve successfully, and method selection on the receiver class hierarchy will always find a hashCode method. And, a strict reading of 15.12.4.4 shows that the same method body will be invoked with the Object/'virtual' pairing as with the Foo/'interface' pairing.

      But it's still a surprise that javac acts like it does, because there is no special treatment of Object's methods in:
      - 15.12.2.1, that would cause Object to be the class to be searched (versus Foo being the interface to be searched); or in
      - 15.12.3, that would cause the 'virtual' invocation mode to be used when the "compile-time declaration" is in an interface; or in
      - 13.1, that would cause the "qualifying type of the method invocation" to be Object rather than Foo.

            abuckley Alex Buckley
            abuckley Alex Buckley
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: