Groovy编译器似乎不喜欢这种通用方法。
@CompileStatic
class GroovyMain {
enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE }
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
static void main(String... args) {
Planet p = getEnumValueFor('Venus', Planet.&valueOf, Planet.EARTH)
Day d = getEnumValueFor('Sunday', Day.&valueOf, Day.MONDAY)
println "$p $d"
}
static <T extends Enum<T>> T getEnumValueFor(String value, Closure<T> closure, T defaultValue) {
try {
return closure.call(value.toUpperCase())
} catch (Exception ignore) {
return defaultValue
}
}
}
我至少可以通过三种方式“修复”该问题。
@CompileStatic
extends Enum<T>
但是这些选项会降低或消除字体安全性。还有另一种方法可以满足groovy编译器的要求吗?
作为参考,等效的Java代码可以正确编译。
class JavaMain {
enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE }
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
public static void main(String... args) {
Planet p = getEnumValueFor("Venus", Planet::valueOf, Planet.EARTH);
Day d = getEnumValueFor("Sunday", Day::valueOf, Day.MONDAY);
System.out.print("" + p + ' ' + d);
}
static <T extends Enum<T>> T getEnumValueFor(String value, Function<String, T> closure, T defaultValue) {
try {
return closure.apply(value.toUpperCase());
} catch (Exception ignore) {
return defaultValue;
}
}
}