开发者

Using enum values to represent binary operators or functions

开发者 https://www.devze.com 2022-12-22 12:20 出处:网络
I\'m looking for an elegant way to use values in a Java enum to represent operations or functions. My guess is, since this is Java, there just isn\'t going to be a nice way to do it, but here goes any

I'm looking for an elegant way to use values in a Java enum to represent operations or functions. My guess is, since this is Java, there just isn't going to be a nice way to do it, but here goes anyway. My enum looks something like this:

public enum Operator {
    LT,
    LTEQ,
    EQEQ,
    GT,
    GTEQ,
    NEQ;

    ...
}

where LT means < (less than), LTEQ means <= (less than or equal to), etc - you get the idea. Now I want to actually use these enum values to apply an operator. I know I could do this just using a whole bunch of if-statements, but that's the ugly, OO way, e.g.:

int a = ..., b = ...;
Operator foo = ...; // one of the enum values
if (foo == Operator.LT) {
    return a < b;
}
else if (foo == Operator.LTEQ) {
    return a <= b;
}
else if .开发者_StackOverflow中文版.. // etc

What I'd like to be able to do is cut out this structure and use some sort of first-class function or even polymorphism, but I'm not really sure how. Something like:

int a = ..., b = ...;
Operator foo = ...;
return foo.apply(a, b);

or even

int a = ..., b = ...;
Operator foo = ...;
return a foo.convertToOperator() b;

But as far as I've seen, I don't think it's possible to return an operator or function (at least, not without using some 3rd-party library). Any suggestions?


Not only is this possible, it's used as an example in the frequently referenced Effective Java, Second Edition by Josh Bloch. I don't want to step on his copyright, will look for a similar example online...

Okay, the code I remembered is freely available at the website I linked earlier. Click "Download the code samples used in this book", then look at effective2/examples/Chapter6/Item30/Operation.java.


int a = ..., b = ...;
Operator foo = ...;
return foo.apply(a, b);

it is possible to do this if foo is object and Operator is base class and concrete operators are concrete classes that implement apply.

0

精彩评论

暂无评论...
验证码 换一张
取 消