【问题标题】:static imports method overlap静态导入方法重叠
【发布时间】:2012-01-31 19:05:59
【问题描述】:

如果您有一个静态导入到java.lang.Integer 的类,而我的类也有一个静态方法parseInt(String),那么调用parseInt("12345") 将指向哪个方法?

提前致谢!

【问题讨论】:

    标签: java import method-signature static-import method-declaration


    【解决方案1】:

    如果您在自己的班级中,它将调用 您的 方法。
    如果您不在您的班级(并导入两个班级),则必须指定要使用的班级。

    证明:http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf $8 和 $6.3(见 cmets)

    【讨论】:

    • 你能提供一个参考,表明它是由标准保证的吗?它可能取决于编译器......
    • 等待sm1回复amit
    • 来自 Java 语言规范 $8:成员的范围(第 6.3 节)(第 8.2 节)是该成员所属类的声明的整个主体。 |从 $6.3 开始:声明的范围是程序的区域,在该区域内,声明所声明的实体可以使用简单名称来引用(前提是它是可见的(§6.3.1))。
    • @Paranaix:请添加指向规范的链接并将其添加到您的答案中,您会得到我的 +1。在我看来,这是一个经过充分验证的答案。
    • 我认为它仍然错过了一点(来自 jls):§6.3.1 A declaration d of a method named n shadows the declarations of any other methods named n that are in an enclosing scope at the point where d occurs throughout the scope of d.
    【解决方案2】:

    试试这个:

    import static java.lang.Integer.parseInt;
    
    public class Test {
        public static void main(String[] args) {
            System.out.println(parseInt("12345"));
        }
    
        private static int parseInt(String str) {
            System.out.println("str");
            return 123;
        }
    }
    

    结果:

    str
    123
    

    类中的方法首先执行。

    【讨论】:

    • 你能提供一个参考,表明它是由标准保证的吗?它可能取决于编译器......