避免 Java 中的重复导入:继承导入?
有没有办法“继承”导入?
示例:
通用枚举:
public enum Constant{ ONE, TWO, THREE }
使用此枚举的基类:
public class Base {
protected void register(Constant c, String t) {
...
}
}
需要导入的子类可以方便地使用枚举常量(没有枚举名称):
import static Constant.*; // want to avoid this line!
public Sub extends Base {
public Sub() {
register(TWO, "blabla"); // without import: Constant.TWO
}
}
以及具有相同导入的另一个类...
import static Constant.*; // want to avoid this line!
public AnotherSub extends Base {
...
}
我可以使用经典的静态最终常量,但也许有一种方法可以同样方便地使用通用枚举。
Is there a way to "inherit" imports?
Example:
Common enum:
public enum Constant{ ONE, TWO, THREE }
Base class using this enum:
public class Base {
protected void register(Constant c, String t) {
...
}
}
Sub class needing an import to use the enum constants convenient (without enum name):
import static Constant.*; // want to avoid this line!
public Sub extends Base {
public Sub() {
register(TWO, "blabla"); // without import: Constant.TWO
}
}
and another class with same import ...
import static Constant.*; // want to avoid this line!
public AnotherSub extends Base {
...
}
I could use classic static final constants but maybe there is a way to use a common enum with the same convenience.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
import
只是帮助编译器查找类。它们对单个源文件有效,并且与 Java 的 OOP 机制没有任何关系。所以,不,你不能“继承”
导入
import
s are just an aid to the compiler to find classes. They are active for a single source file and have no relation whatsoever to Java's OOP mechanisms.So, no, you cannot “inherit”
import
s如果您使用的是 Eclipse,请使用“组织导入”(Ctrl+Shift+O) 让 IDE 为您执行导入(或使用代码完成 (Ctrl+Space)
If you're using Eclipse, use "Organize Imports" (Ctrl+Shift+O) to let the IDE do the imports for you (or use code completion (Ctrl+Space)
不,您不能继承导入。如果要在类文件中引用类型而不使用完全限定名称,则必须显式导入它。
但在你的例子中很容易说
No, you can't inherit an import. If you want to reference a type within a class file without using the fully-qualified name, you have to import it explicitly.
But in your example it would be easy enough to say