作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个类(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 Function
和 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
因为这个答案: 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/
我是一名优秀的程序员,十分优秀!