自动导入包的顺序和歧义 [英] Order of automatically imported packages and ambiguity

查看:127
本文介绍了自动导入包的顺序和歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JLS:第7章。 :


包由许多编译单元组成(第7.3节)。编译单元自动访问其包中声明的所有类型也会自动导入预定义包java.lang 中声明的所有公共类型。

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!
}

如果我移动 MyClass com.example 进入 com.example.p2 并使用 import com导入它。 example.p2。* ,我得到错误:MyClass类型在使用它的地方。

If I move MyClass from com.example into com.example.p2 and import it with import com.example.p2.*, I get Error: the type MyClass is ambigious at the place where it is used.

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

It seems that the Types from the package itself always have precedence over any other imported types, be it automatically from java.lang or be it explicitly with a wildcard import, and that the compiler does not emit any warning or error.

问题:


  • 为什么java编译器在这种情况下不会发出歧义错误?

  • JLS中定义了哪种行为?

推荐答案

表格的进口报表:

import packageName.subPackage.*

类型 - 按需导入声明。即,仅当当前编译单元的范围内没有该类型时,才会导入类或其中的任何类型。

is Type-Import-on-Demand Declarations. i.e, the classes or any types from them will be imported only when that type is not available in the scope of current compilation unit.

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


声明可能被类型的单一类型导入声明所遮蔽其简单名称为Vector; 由名为Vector的类型并在编译单元所属的包中声明;或任何嵌套的类或接口。

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 类class,然后在该类中使用 String ,将引用您的类,因为 java.lang.String 将不会进口。它只会在需求上导入,如 > JLS§ 6.4.1 - 阴影

So, if you have a class String in the same package as your class, then using String in that class, will refer to your class, as java.lang.String will not be imported. It will only be imported on demand, as shown in example 6.4.1-2 of JLS § 6.4.1 - Shadowing.

这篇关于自动导入包的顺序和歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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