使用单个语句更方便,更简洁,比如

import java.awt.*;

而不是导入一堆单独的类

import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...

在import语句中使用通配符有什么问题?


当前回答

最重要的是导入java.awt。*可以使您的程序与未来的Java版本不兼容:

假设你有一个名为“ABC”的类,你使用的是JDK 8,你导入java.util.*。现在,假设Java 9出来了,它在包Java中有一个新类。直到它碰巧也被称为“ABC”。您的程序现在不能在Java 9上编译,因为编译器不知道您的“ABC”名称是指您自己的类还是Java .awt中的新类。

如果只从java显式地导入这些类,就不会遇到这个问题。你实际使用的。

资源:

Java进口

其他回答

郑重声明: 当您添加导入时,您也在指示您的依赖项。

您可以很快看到文件的依赖关系(不包括相同名称空间的类)。

It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import. It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import. It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers. The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.

我工作过的大多数使用大量Java的地方都将显式导入作为编码标准的一部分。我有时仍然使用*来快速创建原型,然后在产品化代码时展开导入列表(一些ide也会为您这样做)。

以下是我关于这个话题的一些发现。

During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code. In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports. Using .* import helps to make code more cleaner Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages. import java.util.*; import java.sql.*; public class DateDemo { private Date utilDate; private Date sqlDate; }

唯一的问题是它会混淆本地名称空间。例如,假设您正在编写一个Swing应用程序,因此需要java.awt。事件,并且还与公司的日历系统进行接口,该系统具有com.mycompany.calendar.Event。如果你使用通配符方法导入两者,会发生以下三种情况之一:

event和com.mycompany.calendar之间存在完全的命名冲突。事件,因此您甚至无法编译。 您实际上只导入了一个(两个导入中只有一个导入了。*),但它是错误的,并且您很难弄清楚为什么代码声称类型是错误的。 在编译代码时,没有com.mycompany.calendar。事件,但当他们后来添加一个时,您以前有效的代码突然停止编译。

显式列出所有导入的好处是,我可以一眼看出您打算使用哪个类,这使得代码的阅读更加容易。如果您只是在做一个快速的一次性的事情,那么没有什么明显的错误,但是未来的维护者会因为您的清晰而感谢您。

请参阅我的文章“按需进口是邪恶的”

简而言之,最大的问题是当一个类被添加到您导入的包中时,您的代码可能会中断。例如:

import java.awt.*;
import java.util.*;

// ...

List list;

在Java 1.1中,这很好;在java中找到列表。啊,没有冲突。

现在假设您检入了运行良好的代码,一年后,其他人使用Java 1.2编辑了它。

Java 1.2在Java .util中添加了一个名为List的接口。繁荣!冲突。完美工作的代码不再工作。

这是一个邪恶的语言特性。没有理由仅仅因为一个类型被添加到包中就停止编译……

此外,它使读者难以确定您使用的是哪个“Foo”。