简体   繁体   English

为什么要导入像 NullPointerException 这样的 java.lang 类?

[英]Why import java.lang classes like NullPointerException?

The Java Language Specification says:Java 语言规范说:

Every compilation unit implicitly imports every public type name declared in the predefined package java.lang, as if the declaration import java.lang.*;每个编译单元都会隐式导入在预定义的 package java.lang 中声明的每个公共类型名称,就像声明 import java.lang.* 一样; appeared at the beginning of each compilation unit immediately after any package statement.在任何 package 语句之后立即出现在每个编译单元的开头。 As a result, the names of all those types are available as simple names in every compilation unit.因此,所有这些类型的名称在每个编译单元中都可以作为简单名称使用。

From time to time, however, I see code that imports classes from java.lang such as import java.lang.NullPointerException;但是,有时我会看到从java.lang导入类的代码,例如import java.lang.NullPointerException; . . Is there any good reason for doing so?这样做有什么好的理由吗?

Is there any good reason for doing so?这样做有什么好的理由吗?

Almost certainly no.几乎可以肯定没有。 The only possible explanation is that they have defined their own NullPointerException in the current package and they don't want to use it in the current class.唯一可能的解释是他们在当前的 package 中定义了自己的NullPointerException ,并且他们不想在当前的 class 中使用它。 (And you shouldn't do that...) (而且你不应该那样做......)

The most likely explanation is that someone doesn't understand Java.最可能的解释是有人不理解Java。

It could also be explained by an IDE suggesting bogus imports 1 .它也可以通过 IDE 来解释,暗示进口1 But that should be picked up by code-review, so if you see it in a published code-base that is a potential code quality red-flag.但这应该通过代码审查来获取,因此如果您在已发布的代码库中看到它,这是一个潜在的代码质量危险信号。

It could also be explained if the code is produced by a source code generator rather than being written by a human.如果代码是由源代码生成器生成而不是由人编写的,也可以解释。 This is excusable, provided that it doesn't result in buggy code.这是可以原谅的,只要它不会导致错误的代码。


1... though I've never seen an IDE do this for java.lang classes. 1 ...虽然我从未见过 IDE 为java.lang类执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM