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

import java.awt.*;

而不是导入一堆单独的类

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

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


当前回答

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

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

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

// ...

List list;

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

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

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

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

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

其他回答

在以前的项目中,我发现将*-imports更改为特定的导入可以将编译时间减少一半(从大约10分钟减少到大约5分钟)。*-import使编译器搜索列出的每个包,以查找与您使用的类相匹配的类。虽然这段时间可能很小,但对于大项目来说,它会累积起来。

*-import的一个副作用是开发人员会复制和粘贴常用的导入行,而不是考虑他们需要什么。

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

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

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

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

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也会为您这样做)。

导入包中的所有类被认为是一种盲目的方法。这样做的一个主要原因是,它会使类名称空间变得混乱,并可能导致具有相同名称的不同包中的类之间发生冲突。

具体地填充必要的类可以避免这个问题,并清楚地显示需要哪些版本。这有利于代码的可维护性。