才疏学浅,目前为止没见过谁在项目中这样写代码,应该是违反代码简洁易懂的原则的,Enum应该保持他绝对不变,安全的特性,但不用,不代表不该看。(本文内容摘自Effective Java 第六章38条)
public class EnumImplInterface {
public static void main(String[] args) {
test(BasicOperation.class,15,8);
test(ExtendedOperation.class,15,8);
System.out.println("枚举中的加法:"+BasicOperation.valueOf("PLUS").apply(15, 8));
}
private static <T extends Enum<T> & Operation> void test(Class<T> opEnumType, double x, double y){
for (Operation operation : opEnumType.getEnumConstants()) {
System.out.println(opEnumType.getName()+":"+operation.apply(x,y));
}
}
}
interface Operation{
double apply(double x, double y);
}
enum BasicOperation implements Operation {
PLUS("+"){
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-"){
@Override
public double apply(double x, double y) {
return x - y;
}
};
BasicOperation(String s) {
}
}
enum ExtendedOperation implements Operation {
EXP("^"){
@Override
public double apply(double x, double y) {
return x % y;
}
};
ExtendedOperation(String s) {
}
}
<T extends Enum<T> & Operation> 确保了Class对象 既表示枚举又表示Operation的子类型。
输出结果:
第六章枚举和注解.BasicOperation:23.0
第六章枚举和注解.BasicOperation:7.0
第六章枚举和注解.ExtendedOperation:7.0
枚举中的加法:23.0