简体   繁体   中英

Import Java classes once for all package

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

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?

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.

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.

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 ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM