使用单个语句更方便,更简洁,比如
import java.awt.*;
而不是导入一堆单独的类
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
在import语句中使用通配符有什么问题?
使用单个语句更方便,更简洁,比如
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”。
其他回答
它使您的名称空间变得混乱,要求您完全指定任何有歧义的类名。最常见的情况是:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
它还有助于使依赖项具体化,因为所有依赖项都列在文件的顶部。
以下是我关于这个话题的一些发现。
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; }
在双方提出的所有有效观点中,我还没有找到避免通配符的主要原因:我喜欢能够阅读代码并直接知道每个类是什么,或者如果它的定义不在语言或文件中,那么在哪里可以找到它。如果用*导入了多个包,我必须搜索它们中的每一个,以找到我不认识的类。可读性是至高无上的,我同意代码不应该需要IDE来读取。
我更喜欢特定的导入,因为它允许我查看文件中使用的所有外部引用,而无需查看整个文件。(是的,我知道不一定会有完全合格的推荐信。但我尽量避免使用。)
郑重声明: 当您添加导入时,您也在指示您的依赖项。
您可以很快看到文件的依赖关系(不包括相同名称空间的类)。