我会尽量保持简短。我正在尝试做这样的事情:
public enum Fruit {
APPLE("Apple", appleHelper::doAppleThing),
ORANGE("Orange", orangeHelper::doOrangeThing);
private String name;
private Function<String, List<T>> fruitFunction;
Fruit(String name, Function<String, List<T>> fruitFunction) {
this.name = name;
this.fruitFunction = fruitFunction;
}
public String getName() {
return name;
}
public <T> List<T> applyFruitFunction(String someString) {
return fruitFunction.apply(someString);
}
}
这样以后,我可以有一个方法
private <T> List<T> doFruitThing(String someString, Fruit fruit) {
List<T> transformedFruits = fruit.applyFruitFunction(someString);
if (transformedFruits.isEmpty()) {
throw new FruitException("There was no fruit of type " + fruit.getName());
}
return transformedFruits;
}
我在这里遇到了两个问题。
doAppleThing而doOrangeThing不是静态的方法,最好将保持下去,我无法找到创建的本地实例的任何方式appleHelper,并orangeHelper让方法参考工作。
即使我将方法设为静态,枚举也不能具有 Type 参数,因此无法将其Function<String, List<T>> fruitFunction作为字段。
有没有办法做到这一点?或者有更好的方法来解决这个问题?
相关分类