Java import all from all

让人想犯罪 __ 提交于 2019-12-20 03:07:21

问题


I have a logical question: Why i cannot import all packages from all packages in java? For example i can import all classes from java.awt:

import java.awt.*;

But the following isnt possible:

import java.awt.*.*;

My aim would be to import all stuff from awt.image and awt.event and so on. Is there another way to do this?

Thank you!


回答1:


There is no way to achieve an import a.package.*.*; in Java. The JLS, Section 7.5 specifies the only 4 types of imports that are legal:

A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name (§6.7).

e.g. import java.util.List;

A type-import-on-demand declaration (§7.5.2) imports all the accessible types (§6.6) of a named type or named package as needed, by mentioning the canonical name of a type or package.

e.g. import java.awt.*;

A single-static-import declaration (§7.5.3) imports all accessible static members with a given name from a type, by giving its canonical name.

e.g. import static org.junit.Assert.assertEquals;

A static-import-on-demand declaration (§7.5.4) imports all accessible static members of a named type as needed, by mentioning the canonical name of a type.

e.g. import static org.junit.Assert.*;

Packages allow classes of the same name to be referenced individually. E.g. there is java.awt.List and java.util.List. What would stop someone from importing everything with java.*.*;. How would List be resolved then? There would be too much ambiguity.




回答2:


No, and using wildcard imports is bad style in general as it makes your code harder to read.




回答3:


Some disadvantages of using wildcards imports:

  1. Results in including classes that you might not use at all. Not clear picture of what you are working with.
  2. More broader scope which is considered bad programming practice.
  3. Most important can result in namespace clash. If you are blatantly importing everything from two packages it may result in clash between two classes with same name from different packages.

Edit: Seems like importing more classes than required doesn't result in any bulky code, but I would still prefer to import the classes explicitly to have a clear idea about what I am working with.



来源:https://stackoverflow.com/questions/19457547/java-import-all-from-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!