简体   繁体   English

如何访问另一个 class 中的枚举?

[英]How to access the enum in another class?

I have the following enum:我有以下枚举:

enum NamesEnum {
    First(1),
    Second(2),
    Third(3),
    Fourth(4),
    static Map<Integer, NamesEnum> valueMap = new HashMap<Integer, NamesEnum();

In another class, I want to access the Fourth using Fourth so that I can get its value of 4 .在另一个 class 中,我想使用Fourth访问 Fourth ,以便获得其值4 In the Enum I have get methods for me to access that enum.在枚举中,我获得了访问该枚举的方法。

If you can declare your enum as public like如果您可以将您的枚举声明为public ,例如

public enum NamesEnum {
   //...
}

you can access the contents like您可以访问以下内容

NamesEnum.Fourth

If you want to get the number 4 from NamesEnum.Fourth , you need to expose the stored value somehow.如果您想从NamesEnum.Fourth获取数字4 ,您需要以某种方式公开存储的值。 You can do so like this:你可以这样做:

public enum NamesEnum {

   First(1),
   Second(2),
   Third(3),
   Fourth(4),

   private final int value;

   NamesEnum(final int Value) {
        value = Value;
   }

   public int getValue() { return value; }
}

and

Names.Fourth.getValue();

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

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