【发布时间】:2016-05-02 10:17:17
【问题描述】:
我有一个可以调用的方法数组,需要一个布尔值作为参数。我试过这个:
public class Example {
public Function<Boolean, Integer> getFunctions(boolean t) {
return new Function[] {
this::magicNumber
};
}
public int magicNumber(boolean t) {
return (t) ? new Random().nextInt(11) : 0;
}
}
但是随后编译器会返回一条错误消息和消息
Incompatible types: invalid method reference
Incompatible types: Object cannot be converted to boolean
然而,上面的例子可以通过将函数存储在一个变量中并返回它来工作,但是我没有找到这个干净的代码而且它是多余的。
public class Example {
public Function<Boolean, Integer> getFunctions(boolean t) {
Function<Boolean, Integer> f = this::magicNumber;
return new Function[] {
f
};
}
public int magicNumber(boolean t) {
return (t) ? new Random().nextInt(11) : 0;
}
}
有什么办法可以像开头的例子那样缩短上面的代码吗?
编辑
根据评论者的要求,我将举一个简短的例子来说明我在以前的项目中如何使用供应商。我将它们返回到一个数组中以返回对象。问题是这个项目依赖于有一个参数。
public Supplier<T>[] getRecipes()
{
return new Supplier[] {
this::anchovyRule,
this::codRule,
this::herringRule,
this::lobsterRule,
this::mackerelRule,
this::pikeRule,
this::salmonRule,
this::sardineRule,
this::shrimpRule,
this::troutRule,
this::tunaRule
};
}
【问题讨论】:
-
我会先编译你的示例。为什么在
getFunctions中忽略t? -
@Tunaki 我想返回一个函数数组,就像我在第一个代码块中展示的那样。
-
@GamerNebulae 如 Tunaki 所示,数组和泛型不能很好地混合。除非有特定原因需要它是一个数组,否则请改用
List<Function<Boolean, Integer>>之类的集合。
标签: java