Java静态导入 [英] Java static imports

查看:140
本文介绍了Java静态导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过实验,我发现即使在静态上下文中,Java非静态方法也会覆盖范围内所有相同的命名方法。即使不允许参数重载。喜欢

Just by experiment I discovered that Java non static methods overrides all same named methods in scope even at static context. Even without allowing parameter overloading. Like

import java.util.Arrays;    
import static java.util.Arrays.toString;

public class A {
    public static void bar(Object... args) {
        Arrays.toString(args);
        toString(args);     //toString() in java.lang.Object cannot be applied to (java.lang.Object[])
    }
}

我在规范中找不到任何相关内容。这是一个错误吗?如果不是,是否有任何理由来实现这样的语言?

I can't find anything about this in spec. Is this a bug? If it isn't, are there any reasons to implement language like that?

UPD:Java 6不编译此示例。问题是 - 为什么?

推荐答案

解释很简单,虽然它不会改变行为这一事实是非常不直观的:

The explanation is simple although it doesn't change the fact that the behavior is highly unintuitive:

在解析要调用的方法时,编译器所做的第一件事就是找到具有正确名称方法的最小封闭范围。只有这样才会出现重载解析和游戏中的其他内容。

When resolving the method to be invoked the first thing the compiler does is find the smallest enclosing scope that has a method of the right name. Only then come other things like overload resolution and co in game.

现在这里发生的是包含 toString的最小封闭范围( )方法是A类,它从 Object 继承它。因此,我们停在那里,不要再搜索。遗憾的是,接下来编译器会尝试找到给定范围内方法的最佳拟合,并注意到它不能调用任何方法并给出错误。

Now what is happening here is that the smallest enclosing scope that contains a toString() method is class A which inherits it from Object. Hence we stop there and don't search farther. Sadly next the compiler tries to find the best fit of the methods in the given scope and notices that it can't call any of those and gives an error.

这意味着什么从不静态导入名称与Object中的方法相同的方法,因为自然在范围内的方法优先于静态导入(JLS详细描述方法阴影) ,但对于这个问题,我认为只记得这个问题要简单得多。

Which means never statically import methods with a name that is identical to a method in Object, because methods that are naturally in scope take precedence over static imports (the JLS describes method shadowing in detail, but for this problem I think it's much simpler to just remember that).

编辑: @ alf 亲切地提交了JLS的正确部分描述了那些想要全局的人的方法调用。它相当复杂,但问题并不简单,所以这是预期的。

@alf kindly submitted the right part of the JLS that describes the method invocation for those who want the whole picture. It's rather complex, but then the problem isn't simple either so that's to be expected.

这篇关于Java静态导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆