简体   繁体   English

我可以静态导入私有子类吗?

[英]Can I do a static import of a private subclass?

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
  }
}

You can use the no-modifier access level, ie 您可以使用no-modifier访问级别,即

enum MyEnum { DOG, CAT }

MyEnum will not be visible to classes from other packages neither from any subclass. 对于来自其他包的类, MyEnum都不会从任何子类中看到。 It is the closest form of private, yet letting you avoid explicitly referencing MyEnum . 它是最接近私有的形式,但让你避免明确引用MyEnum

Or is there a better way to write this? 或者有更好的方法来写这个吗?

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. 如果您的主要目标是引用没有限定枚举标识符的项目,并私下维护此列表,则可以完全废弃enum类型并使用普通的私有静态常量。

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. 如果按下,则可以复制外部类中的静态字段。

private static final MyEnum CAT = MyEnum.CAT;
private static final MyEnum DOG = MyEnum.DOG;

Icky, but a possibility. Icky,但有可能。

不,这几乎就是private所有。

You could simply write your code inside the enum itself. 你可以简单地在enum本身内编写你的代码。

public enum MyEnum {
DOG, CAT;
public static void main(String[] args) {
    MyEnum dog = MyEnum.DOG; // this works but I don't want to have to type
                                // MyEnum
    MyEnum cat = CAT; // compile error, but this is what I want to do
}
 }

The other place where private enums can be references without their class is in a switch statement: 私有枚举可以在没有类的情况下引用的另一个地方是switch语句:

private static enum MyEnum {
    DOG, CAT
}

public static void main(String[] args) {
    MyEnum e = null;
    switch (e) {
    case DOG:
    case CAT:
    }
}

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

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