Java:编译时解析和"最具体的方法"

Jas*_*n S 5 java subtype jls language-lawyer

重载的功能compute1(),compute2()以及compute5()导致编译错误,如果您尝试使用以下这些:

package com.example.test.reflect;

class JLS15Test2
{
    int compute1(Object o1, Integer i, Integer j)         { return 1; }
    int compute1(String s1, Integer i, int j)             { return 2; }

    int compute2(Object o1, Integer i, int j)             { return 3; }
    int compute2(String s1, Integer i, Integer j)         { return 4; }

    int compute3(Object o1, Integer i, int j)             { return 5; }
    int compute3(String s1, Integer i, int j)             { return 6; }

    int compute4(Object o1, Integer i, Integer j)         { return 7; }
    int compute4(String s1, Integer i, Integer j)         { return 8; }

    int compute5(Object o1, Integer i, Object j)          { return 9; }
    int compute5(String s1, Integer i, int j)             { return 10; }


    public static void main(String[] args) 
    {
        JLS15Test2 y = new JLS15Test2();

        // won't compile:
        // The method compute1(Object, Integer, Integer) is ambiguous 
        // for the type JLS15Test2
        // System.out.println(y.compute1("hi", 1, 1));

        // Neither will this (same reason)
        // System.out.println(y.compute2("hi", 1, 1));
        System.out.println(y.compute3("hi", 1, 1));
        System.out.println(y.compute4("hi", 1, 1));

        // neither will this (same reason)
        // System.out.println(y.compute5("hi", 1, 1));
    }
}
Run Code Online (Sandbox Code Playgroud)

在阅读JLS第15.12节之后,我想我理解......在第2阶段(装箱/取消装箱允许,没有varargs)匹配重载方法,在确定"最具体的方法"时,JLS说(实际上)最多特定方法是其形式参数是其他适用方法的子类型的方法,而原语和对象(例如intInteger)从不是彼此的子类型.因此Integer是w/r/t子类型比较的子类型Integer,并且int是子类型int,但是Integer并且int是不兼容的,因此这两个compute1()/ compute2()对都没有最具体的方法.

(而在compute3()compute4()与该方法String的参数是比用该方法更具体的Object参数,所以在打印程序6和8)

我的推理是否正确?

Ste*_*nes 0

是的,你的推理是正确的。