gpt4 book ai didi

java - Enum 中没有枚举 const 类

转载 作者:行者123 更新时间:2023-12-01 07:36:29 26 4
gpt4 key购买 nike

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");

它抛出上述异常。有什么想法吗?

最佳答案

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

关于java - Enum 中没有枚举 const 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11268118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com