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

现在当我尝试打电话时

ProcessorFactory.getProcessor("ap");

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

4

2 回答 2

4

尝试ProcessorFactory.getProcessor("A")

或添加新方法:

public ProcessorFactory getbyProduct(String product) {
   for (ProcessorFactory factory : values()) {
      if (factory.getProduct().equals(processor)) {
         return factory;
      }
   }
   return null; // or throw an exception
}
于 2012-06-29T19:57:35.720 回答
3

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

于 2012-06-29T19:58:26.723 回答