我有两个不同的枚举:
public enum A {
mass(10); // many other values omitted for clarity
private final int m;
private A(int m) { this.m = m; }
public int value() { return this.m; }
}
public enum B {
mass(100); // many other values omitted for clarity
private final int m;
private B(int m) { this.m = m; }
public int value() { return this.m; }
}
并希望将枚举类作为参数传递给我的函数。从我在SO上找到的其他答案,建议我可以传递Class,但我不确定如何在函数体中正确检测和使用A或B枚举:
public int mass(Class<?> clazz) {
// Is it the best way? How to avoid a bunch of ifs?
if (clazz == A.class) return A.mass.value();
if (clazz == B.class) return B.mass.value();
}
答案 0 :(得分:3)
不确定你想要完成什么,但你似乎需要多态性。尝试使用Enums的界面,如下所示:
public enum A implements MassProvider {
MASS(10);
private int mass;
A(int mass) {
this.mass = mass;
}
@Override
public int getMass() {
return mass;
}
}
public enum B implements MassProvider {
MASS(100);
private int mass;
B(int mass) {
this.mass = mass;
}
@Override
public int getMass() {
return mass;
}
}
public interface MassProvider {
int getMass();
}
public static int mass(MassProvider p) {
return p.getMass();
}
基本上,不是将类传递给mass方法,而是传递由两个枚举实现的MassProvider。