如何解决BiConsumer lambda函数中的“对象无法转换”?

时间:2018-06-18 04:11:27

标签: java generics lambda

我有一个类(Filter),它有几个变量:

class Filter {
    Integer intVal;
    Double doubleVal;
    String strVal;

    public Integer getIntVal() {
        return intVal;
    }

    public void setIntVal(Integer intVal) {
        this.intVal = intVal;
    }

    public Double getDoubleVal() {
        return doubleVal;
    }

    public void setDoubleVal(Double doubleVal) {
        this.doubleVal = doubleVal;
    }

    public String getStrVal() {
        return strVal;
    }

    public void setStrVal(String strVal) {
        this.strVal = strVal;
    }
}

需要包含lambda HandlerFunction以获取和设置值的类(BiConsumer):

class Handler {
    Function<Filter, Object> getter;
    BiConsumer<Filter, Object> setter;
    public Handler(Function<Filter, Object> getter, BiConsumer<Filter, Object> setter) {
        this.getter = getter;
        this.setter = setter;
    }
}

(我使用BiConsumer因为这个SO回答:https://stackoverflow.com/a/27759997/963076)。

像这样实施:

Filter filter = new Filter();

Handler handler1 = new Handler(Filter::getIntVal, Filter::setIntVal);
Object o = handler1.getter.apply(filter);
handler1.setter.accept(filter, o);
Handler handler2 = new Handler(Filter::getDoubleVal, Filter::setDoubleVal);
Handler handler3 = new Handler(Filter::getStrVal, Filter::setStrVal);

但是制定者不起作用。编译器抛出错误:

error: incompatible types: invalid method reference
Handler handler1 = new Handler(Filter::getIntVal, Filter::setIntVal);
incompatible types: Object cannot be converted to Integer

error: incompatible types: invalid method reference
Handler handler2 = new Handler(Filter::getDoubleVal, Filter::setDoubleVal);
incompatible types: Object cannot be converted to Double

error: incompatible types: invalid method reference
Handler handler3 = new Handler(Filter::getStrVal, Filter::setStrVal);
incompatible types: Object cannot be converted to String

因此BiConsumer无法强制Object转换为String等等。那么我该如何解决这个问题呢?我该怎么写这个,以便我可以用lambda函数设置Filter的值?

非常肯定答案与仿制药有关,而我有时很难将其包裹起来。

1 个答案:

答案 0 :(得分:3)

通知您的处理程序

    Handler<Integer> handler1 = new Handler<>(Filter::getIntVal, Filter::setIntVal);
    Integer i1 = handler1.getter.apply(filter);
    handler1.setter.accept(filter, i1);

以下是示例用法

order by