我正在使用BiFunction来发送函数。
我现在拥有的是:
public class Animal {
public static String cat(
final String field,
final Object value
) {
return "(CAT:" + field + toString(value) + ")";
}
public static String dog(
final String field,
final Object value
) {
return "(DOG:" + field + toString(value) + ")";
}
}
public String getAnimal(
final String animalFieldName,
final BiFunction<String, Object, String> function,
final Object animelieldValue
) {
return function.apply(animalFieldName, animalFieldValue);
}
我这样用它:
new Animal("catName", Animal::cat, "catti")
我想要的是BiFunction&lt;&gt;将是一个枚举, 所以getAnimal()的签名将是:
String getAnimal(
final String animalFieldName,
/* Enum that has values that are BiFunctions, */
final Object animalFieldValue
)
有什么建议吗?我会很感激代码示例。
答案 0 :(得分:3)
不太确定你想要什么,但这似乎符合要求?
enum Animal implements BiFunction<String, Object, String> {
CAT,
DOG,
BEAR {
@Override
public String apply(String s, Object o) {
return "This is a Bear!!!";
}
};
@Override
public String apply(String s, Object o) {
return "(" + name() + ":" + s + o.toString() + ")";
}
}
public void test() {
for (Animal animal : Animal.values()) {
System.out.println(animal.apply("hello", "Hello"));
}
}
答案 1 :(得分:2)
@ OldCurmudgeon的答案的变体,有更多的lambdas:
enum Animal implements BiFunction<String, Object, String> {
CAT,
DOG,
BEAR((s, o) -> "This is a Bear!!!");
private final BiFunction<String, Object, String> function;
private Animal(final BiFunction<String, Object, String> function) {
this.function = function;
}
private Animal() {
super((s, o) -> "(" + name() + ":" + s + o.toString() + ")");
}
}
public void test() {
Animal
.values()
.stream(animal -> animal.apply("hello", "Hello"))
.forEach(System.out::println)
;
}