Java import all from all

2019-02-27 09:25发布

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!

3条回答
ゆ 、 Hurt°
2楼-- · 2019-02-27 09:42

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.

查看更多
虎瘦雄心在
3楼-- · 2019-02-27 09:51

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

查看更多
叛逆
4楼-- · 2019-02-27 10:08

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.

查看更多
登录 后发表回答