问题描述
我有这个枚举:
public enum Operator {
add("+", BigDecimal::add),
subtract("-", BigDecimal::subtract),
multiply("*", BigDecimal::multiply),
divide("/", BigDecimal::divide),
mod("%", BigDecimal::remainder);
Operator(final String symbol, final BinaryOperator<BigDecimal> operation) {
this.symbol = symbol;
this.operation = operation;
}
public BinaryOperator<BigDecimal> getOperation() {
return operation;
}
}
我想使用一些MathContext
,当执行这样的操作时,可以很容易地做到这一点:
I want to use the some MathContext
, one can easily do that when performing an operation like this:
MathContext mc = MathContext.DECIMAL32;
BigDecimal t0 = new BigDecimal(100);
BigDecimal t1 = new BigDecimal(2);
BigDecimal result = t0.add(t1, mc);
但是,如果我想在枚举中使用对BinaryOperator
的引用,我看不到给它赋予MathContext
的方法:
However if I want to use the reference to the BinaryOperator
in the enum I can't see a way of giving it the MathContext
:
BigDecimal result = enum.getOperation().apply(t0, t1);
在文档或适用的适用方法中,我看到任何选项.
In the documentation nor the methods available for apply I see any option.
推荐答案
根据用例,可以将自定义功能接口的范围保持在最小:
Depending on the use case, you can keep the scope of the custom functional interface at a minimum:
public enum Operator {
add("+", BigDecimal::add),
subtract("-", BigDecimal::subtract),
multiply("*", BigDecimal::multiply),
divide("/", BigDecimal::divide),
mod("%", BigDecimal::remainder);
private interface TriFunc {
BigDecimal apply(BigDecimal a, BigDecimal b, MathContext c);
}
private String symbol;
private TriFunc operation;
Operator(String symbol, TriFunc operation) {
this.symbol = symbol;
this.operation = operation;
}
public BinaryOperator<BigDecimal> getOperation(MathContext c) {
return (a, b) -> operation.apply(a, b, c);
}
// you can also provide a direct method:
public BigDecimal apply(BigDecimal a, BigDecimal b, MathContext c) {
return operation.apply(a, b, c);
}
}
因此,使用Operator
枚举的任何人都不必了解内部使用的TriFunc
界面. Operator
可以直接使用,就像
So anyone using the Operator
enumeration, doesn’t have to know anything about the internally used TriFunc
interface. Operator
can be use either, directly like
BigDecimal result = Operator.add
.apply(new BigDecimal(100), new BigDecimal(2), MathContext.DECIMAL32);
或获得标准的BinaryOperator<BigDecimal>
之类的
BigDecimal result = Operator.add.getOperation(MathContext.DECIMAL32)
.apply(new BigDecimal(100), new BigDecimal(2));
这篇关于将MathContext设置为BinaryOperator参考方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!