8

假设我有一个 Enum 定义如下:

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.ASample.A.getAVal()不使用问题来提取值。

现在假设它AClass.getValue()可以接受一个参数来返回一个可能不同的特定值,例如AClass.getValue(42).

可以将参数传递给公共 Enum 方法并检索 Enum 值吗?换句话说,我可以有一个像这样的枚举定义吗

    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)

4

3 回答 3

6

您可以这样做,但只能通过在枚举中创建一个抽象方法,并在每个值中覆盖它:

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),那么您可以将代码放入枚举类本身而不是嵌套类中。

于 2013-01-09T16:03:23.837 回答
3

Java规范中所述

每个枚举常量只有一个实例

所以不,您不能有特定枚举常量的不同值。

但是你可以在你的枚举中放置一个数组或一个映射,所以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); 
        }
}
于 2013-01-09T16:00:28.370 回答
-3
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
于 2017-08-09T20:21:52.810 回答