简体   繁体   中英

Why import java.lang classes like NullPointerException?

The Java Language Specification says:

Every compilation unit implicitly imports every public type name declared in the predefined package java.lang, as if the declaration import java.lang.*; appeared at the beginning of each compilation unit immediately after any package statement. 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; . 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. (And you shouldn't do that...)

The most likely explanation is that someone doesn't understand Java.

It could also be explained by an IDE suggesting bogus imports 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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