gpt4 book ai didi

java - 如何在 BiConsumer lambda 函数中获取 "Object cannot be converted"?

转载 作者:行者123 更新时间:2023-12-01 19:52:25 24 4
gpt4 key购买 nike

我有一个类(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;
}
}

还有一个类 (Handler),需要包含 lambda FunctionBiConsumer 来获取和设置值:

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 因为这个答案: 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);

但是 setter 不起作用。编译器抛出错误:

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 的值?

很确定答案与泛型有关,有时我很难理解它。

最佳答案

生成你的处理程序

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

这是示例用法

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

关于java - 如何在 BiConsumer lambda 函数中获取 "Object cannot be converted"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com