gpt4 book ai didi

java - 自动导入包的顺序和歧义

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:27 24 4
gpt4 key购买 nike

JLS: Chapter 7. Packages:

A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

让我们假设以下代码:

package com.example.p1;
public class MyClass { }
package com.example;
public class MyClass { }
package com.example;
public class String { }
package com.example;

import com.example.p1.*;

public class MainNameClash {
private String s; // No Error, even though ambiguous with java.lang.String!
private MyClass m; // No error, even though ambiguous with com.example.p1.MyClass!
}

如果我将 MyClasscom.example 移动到 com.example.p2 并使用 import com.example 导入它。 p2.*,我在使用它的地方得到了Error: the type MyClass is ambigious

似乎包本身的类型总是优先于任何其他导入类型,无论是自动从 java.lang 还是显式地使用通配符导入,而且编译器不会发出任何警告或错误。

问题:

  • 为什么 java 编译器在这种情况下没有发出歧义错误?
  • 此行为在 JLS 中的何处定义?

最佳答案

表单的导入语句:

import packageName.subPackage.*

Type-Import-on-Demand Declarations .即,只有当该类型在当前编译单元的范围内不可用时,才会导入类或其中的任何类型。

仅来自该 JLS 部分的示例 7.5.2-1:

The declaration might be shadowed by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or any nested classes or interfaces.

因此,如果您在与您的类相同的包中有一个类 String,那么在该类中使用 String 将引用您的类,如 java.lang.String 不会被导入。它只会按需求导入,如example 6.4.1-2 所示。的 JLS § 6.4.1 - Shadowing .

关于java - 自动导入包的顺序和歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21477783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com