Java 是否可以将参数传递到枚举值?
假设我定义了一个枚举,如下所示:Java 是否可以将参数传递到枚举值?,java,enums,Java,Enums,假设我定义了一个枚举,如下所示: public enum Sample{ // suppose AClass.getValue() returns an int A(AClass.getValue()), B(AClass.getValue()), C(AClass.getValue()); private int _value; private Sample(int _val){ this._value = _val;
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getValue()),
B(AClass.getValue()),
C(AClass.getValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
我可以使用Sample.A
或Sample.A.getAVal()
毫无问题地提取值
现在假设AClass.getValue()
可以使用一个参数返回一个可能不同的特定值,例如AClass.getValue(42)
是否可以将参数传递给公共枚举方法并检索枚举值?换句话说,我可以有一个枚举定义,如
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getAValue()),
B(AClass.getBValue()),
C(AClass.getCValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public int getVal(int a){
// somehow pull out AClass.getAValue(a)
}
使用中所述的Sample.A.getValue(42)
?
每个枚举常量只有一个实例
因此,不能对特定枚举常量使用不同的值
但是您可以在枚举中放置数组或映射,这样Sample.a.getValue(42)
将返回Sample.a.myMap.get(42)
:
public enum Sample{
A(),
B(),
C();
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public int getVal(int i){
return myMap.get(i);
}
public int setVal(int i, int v){
return myMap.put(i, v);
}
}
公共枚举示例{
A(),
B(),
C();
Map myMap=newhashmap();
公共整数getVal(整数i){
返回myMap.get(i);
}
公共int setVal(int i,int v){
返回myMap.put(i,v);
}
}
您可以这样做,但只能在枚举中创建一个抽象方法,并在每个值中重写它:
public enum Sample {
A(AClass.getAValue()) {
@Override public int getVal(int x) {
return AClass.getAValue(x);
}
},
B(BClass.getAValue()) {
@Override public int getVal(int x) {
return BClass.getBValue(x);
}
},
C(CClass.getAValue()) {
@Override public int getVal(int x) {
return CClass.getCValue(x);
}
};
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public abstract int getVal(int x);
}
当然,如果您可以创建具有
getValue(int x)
方法的某个其他基类型的实例,那么您可以将代码放入enum类本身,而不是嵌套的类中。您的意思是希望具有相同enum值的不同实例吗?听起来您需要一个常量映射,不是枚举。当我写这个问题时,我知道我可能在做一些粗略的事情…谢谢!它确实表明这不是我应该走的路。请提供关于你的代码如何解决问题的解释,仅仅发布没有注释或解释的代码无助于理解如何应用解决方案。
public class App {
public static void main(String[] args) {
Fruit.setCounter(5);
System.out.println(Fruit.Apple.getCmd());
Fruit.setCounter(6);
System.out.println(Fruit.Apple.getCmd());
}
}
public enum Fruit {
Apple {
public String getCmd() {
return counter + " apples";
}
},
Banana {
public String getCmd() {
return counter + " bananas";
}
};
private static int counter = 0;
public abstract String getCmd();
public static void setCounter(int c) {
counter = c;
}
}
Output:
5 apples
6 apples