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

import java.awt.*;

而不是导入一堆单独的类

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

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


当前回答

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

其他回答

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

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

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

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

// ...

List list;

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

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

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

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

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

在双方提出的所有有效观点中,我还没有找到避免通配符的主要原因:我喜欢能够阅读代码并直接知道每个类是什么,或者如果它的定义不在语言或文件中,那么在哪里可以找到它。如果用*导入了多个包,我必须搜索它们中的每一个,以找到我不认识的类。可读性是至高无上的,我同意代码不应该需要IDE来读取。

它使您的名称空间变得混乱,要求您完全指定任何有歧义的类名。最常见的情况是:

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

...
List blah; // Ambiguous, needs to be qualified.

它还有助于使依赖项具体化,因为所有依赖项都列在文件的顶部。

在DDD书中

在实现将基于的任何开发技术中,寻找最小化的方法 重构模块的工作。在Java中,无法逃避导入到单个类中,只能逃避导入到您 一次至少可以导入整个包,以反映包是高度内聚单元的意图吗 同时减少了更改包名的工作量。

如果它弄乱了本地命名空间,那不是你的错——是包的大小造成的。