我可以静态导入私有子类吗?
我有一个私有的枚举,不能暴露在课堂之外。无论如何,我可以执行该类型的静态导入,这样我就不必每次都键入枚举类型吗?或者有更好的方法来写这个吗?例子:
package kip.test;
import static kip.test.Test.MyEnum.*; //compile error
public class Test
{
private static enum MyEnum { DOG, CAT }
public static void main (String [] args)
{
MyEnum dog = MyEnum.DOG; //this works but I don't want to type "MyEnum"
MyEnum cat = CAT; //compile error, but this is what I want to do
}
}
I have an enum which is private, not to be exposed outside of the class. Is there anyway I can do a static import of that type, so that I don't have to type the enum type each time? Or is there a better way to write this? Example:
package kip.test;
import static kip.test.Test.MyEnum.*; //compile error
public class Test
{
private static enum MyEnum { DOG, CAT }
public static void main (String [] args)
{
MyEnum dog = MyEnum.DOG; //this works but I don't want to type "MyEnum"
MyEnum cat = CAT; //compile error, but this is what I want to do
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用无修饰符访问级别,即
MyEnum
对其他包中的类和任何子类中的类均不可见。它是最接近的私有形式,但可以让您避免显式引用MyEnum
。You can use the no-modifier access level, i.e.
MyEnum
will not be visible to classes from other packages neither from any subclass. It is the closest form of private, yet letting you avoid explicitly referencingMyEnum
.考虑到您可以完全限定地访问该字段,我想说这是编译器(或语言规范)中的一个错误,您无法静态导入它。
我建议您对枚举包进行保护。
Considering that you can access the field fully qualified, I would say that it is a bug in the compiler (or language spec) that you cannot statically import it.
I suggest that you make the enumeration package-protected.
将某些代码移至枚举的(静态)方法中可能(也可能不)合理。
如果按下,您可以复制外部类中的静态字段。
恶心,但有可能。
It may (or may not) be reasonable to move some of the code into (static) methods of the enum.
If pressed, you could duplicate the static fields in the outer class.
Icky, but a possibility.
如果您的主要目标是引用没有限定枚举标识符的项目,并私下维护此列表,则可以完全废弃
enum
类型并使用普通的私有静态常量。If your main goals are to reference the items without their qualifying enum identifier, and maintain this list privately, you could scrap the
enum
type altogether and use ordinary private static constants.您可以简单地将代码编写在枚举本身内。
私有枚举可以在没有其类的情况下进行引用的另一个地方是在 switch 语句中:
You could simply write your code inside the enum itself.
The other place where private enums can be references without their class is in a switch statement:
不,这就是
private
的全部内容。Nope, that's pretty much what
private
is all about.