简体   繁体   English

为所有包导入一次Java类

[英]Import Java classes once for all package

Let's say, I have the following structure: 比方说,我有以下结构:

  • src.main.java src.main.java
    • first 第一
      • one.java one.java
      • two.java two.java
      • three.java three.java
    • second 第二
      • alpha.java alpha.java
      • beta.java beta.java
      • gamma.java gamma.java

I want all classes from first package to be imported in all classes in my second package. 我希望first包中的所有类都可以在我的second包中的所有类中导入。

Now I'm just specifying for every class in second package: 现在我只是为second包中的每个类指定:

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. 更好的解决方案是使用可以根据需要添加导入的IDE。

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. 它更好地记录了您的意图,IDE可以使您对它透明。

No, you can't do that in Java. 不, 你不能用Java 做到这一点

One thing that you might think of doing is moving classes from second package to first so you won't need the imports. 您可能想到的一件事是将类从second包移到first包,这样您就不需要导入了。 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? 也许我可以使用import语句创建一些超类,然后每次扩展它?

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. 实际上, import是故意设计的,以这种方式工作。 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 ...) (如果你不使用星级导入,效果最好...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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