方法我有两个不同的枚举:通行证枚举类作为参数传递给Java中
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,建议我可以通过类,但我不知道如何正确检测和使用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();
}
这看起来真的很丑,就好像你不需要这样做,但它应该工作得很好。 – bmargulies
为什么不只是让'A'和'B'实现一个getMass()方法的接口呢? – resueman