Java – can I pass parameters to enum values?
•
Java
Suppose I have an enumeration defined as follows:
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; }
I can use sample A or sample A. Getaval () extracts values without problems
Now suppose aclass GetValue () can use parameters to return specific values that may be different, such as aclass getValue(42).
Can I pass parameters to the public enum method and retrieve enumeration values? In other words, I can define it like 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) }
Use sample A.getValue(42)?
Solution
You can do this, but you can only create an abstract method in the enumeration and override it in each value:
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); }
Of course, if you can create an instance of another base type with a getValue (int x) method, you can put the code in the enumeration class itself instead of the nested class
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码