问题
Let's say, I have the following structure:
- src.main.java
- first
- one.java
- two.java
- three.java
- second
- alpha.java
- beta.java
- gamma.java
- first
I want all classes from first
package to be imported in all classes in my second
package.
Now I'm just specifying for every class in second
package:
import first.*;
Can I import once for all classes in package?
回答1:
No, it cannot be done.
I don't see why this is such a hardship.
A better solution would be to use an IDE that can add the imports as you need them.
I'd also recommend spelling each one out individually rather than using the star notation, even if you need to import all of them. It documents your intent better, and that IDE can make it transparent to you.
回答2:
No, you can't do that in Java.
One thing that you might think of doing is moving classes from second
package to first
so you won't need the imports. But I understand that that is not always possible/desirable.
回答3:
Can I import once for all classes in package?
No you can't. Imports only apply to the class source file in which they are declared.
Maybe I can create some superclass with import statements and then extend it every time?
That will only work if the code in the subclasses does not mention the names of the external types at all ... which is rarely possible.
As I said imports only apply to the class source file in which they are declared.
Actually, the import
was deliberately designed to work this way. The idea is to allow you to easily figure out what class a classname refers to. (It works best if you don't use star imports ...)
来源:https://stackoverflow.com/questions/11933859/import-java-classes-once-for-all-package