java 枚举中没有枚举常量类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11268118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:27:31  来源:igfitidea点击:

No enum const class in Enum

javaenums

提问by RandomQuestion

public enum ProcessorFactory {
    A("ap") {
        Processor create() throws Exception {
            return new AProcessor();
        }
    },

    B("bp"){
        Processor create() throws Exception {
            return new BProcessor();
        }
    };

    abstract Processor create() throws Exception;

    public static Processor getProcessor(String product) throws Exception {
        ProcessorFactory factory = valueOf(product);
        return factory.create();
    }

    private String product;

    private ProcessorFactory(String product) {
        this.product = product;
    }
 }

Now when I try to call

现在当我尝试打电话时

ProcessorFactory.getProcessor("ap");

It throws above exception. Any ideas?

它抛出上述异常。有任何想法吗?

回答by krakover

Try ProcessorFactory.getProcessor("A")

尝试 ProcessorFactory.getProcessor("A")

or add a new method:

或添加一个新方法:

public ProcessorFactory getbyProduct(String product) {
   for (ProcessorFactory factory : values()) {
      if (factory.getProduct().equals(processor)) {
         return factory;
      }
   }
   return null; // or throw an exception
}

回答by eran

Well, there really is no enum value named "ap". You only have Aand B. valueOfdoes not use what you store in product. If you want to get enums by some custom identifier, you'll have to use some translation map that will convert productto ProcessorFactoryvalue (or just go over all values, which is less efficient).

好吧,确实没有名为“ap”的枚举值。你只有ABvalueOf不使用您存储在product. 如果您想通过某些自定义标识符获取枚举,则必须使用一些将转换productProcessorFactory值的转换映射(或者只是遍历所有值,效率较低)。