使用单个语句更方便,更简洁,比如
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语句中使用通配符有什么问题?
当前回答
郑重声明: 当您添加导入时,您也在指示您的依赖项。
您可以很快看到文件的依赖关系(不包括相同名称空间的类)。
其他回答
我更喜欢特定的导入,因为它允许我查看文件中使用的所有外部引用,而无需查看整个文件。(是的,我知道不一定会有完全合格的推荐信。但我尽量避免使用。)
在Java import语句中使用通配符并不坏。
在《Clean Code》中,Robert C. Martin建议使用它们来避免冗长的导入列表。
以下是建议:
J1: Avoid Long Import Lists by Using Wildcards If you use two or more classes from a package, then import the whole package with import package.*; Long lists of imports are daunting to the reader. We don’t want to clutter up the tops of our modules with 80 lines of imports. Rather we want the imports to be a concise statement about which packages we collaborate with. Specific imports are hard dependencies, whereas wildcard imports are not. If you specifically import a class, then that class must exist. But if you import a package with a wildcard, no particular classes need to exist. The import statement simply adds the package to the search path when hunting for names. So no true dependency is created by such imports, and they therefore serve to keep our modules less coupled. There are times when the long list of specific imports can be useful. For example, if you are dealing with legacy code and you want to find out what classes you need to build mocks and stubs for, you can walk down the list of specific imports to find out the true qualified names of all those classes and then put the appropriate stubs in place. However, this use for specific imports is very rare. Furthermore, most modern IDEs will allow you to convert the wildcarded imports to a list of specific imports with a single command. So even in the legacy case it’s better to import wildcards. Wildcard imports can sometimes cause name conflicts and ambiguities. Two classes with the same name, but in different packages, will need to be specifically imported, or at least specifically qualified when used. This can be a nuisance but is rare enough that using wildcard imports is still generally better than specific imports.
郑重声明: 当您添加导入时,您也在指示您的依赖项。
您可以很快看到文件的依赖关系(不包括相同名称空间的类)。
性能:由于字节码相同,对性能没有影响。 尽管这会导致一些编译开销。
编译:在我的个人机器上,编译一个空白类而不导入任何东西需要100毫秒,但导入java时是同一个类。*占用170毫秒。
在双方提出的所有有效观点中,我还没有找到避免通配符的主要原因:我喜欢能够阅读代码并直接知道每个类是什么,或者如果它的定义不在语言或文件中,那么在哪里可以找到它。如果用*导入了多个包,我必须搜索它们中的每一个,以找到我不认识的类。可读性是至高无上的,我同意代码不应该需要IDE来读取。