我想声明一个接受3个参数的函数,并像这样返回一个自定义对象
public static returnResult leadRatingFunction(LeadMaster lead,JSONObject json,String str)
{
}
// Where returnResult and LeadMaster are custom objects
我已在功能界面中声明了此功能,如下所示,
@SuppressWarnings("hiding")
@FunctionalInterface
interface Function<LeadMaster,JSONObject,String,returnResult>
{
public returnResult apply(LeadMaster lead,JSONObject jsonObject,String str);
}
我想将此函数用作这样的哈希映射值,
Map<String, Function<LeadMaster,JSONObject,String,returnResult>> commands = new HashMap<>();
commands.put("leadRating",res -> leadRatingFunction(input1 ,input2 ,input3) ) ;
但它给出了错误,因为“Lambda表达式的签名与应用的功能接口方法的签名不匹配(LeadMaster,JSONObject,String)”
谢谢
答案 0 :(得分:9)
匹配Function<LeadMaster,JSONObject,String,returnResult>
的lambda表达式需要三个参数:
Map<String, Function<LeadMaster,JSONObject,String,returnResult>> commands = new HashMap<>();
commands.put("leadRating",(a,b,c) -> leadRatingFunction(a,b,c));
或者,正如Lino所评论的那样,您可以使用方法参考:
commands.put("leadRating",YourClass::leadRatingFunction);
顺便说一句,我不确定您希望Function<LeadMaster,JSONObject,String,returnResult>
接口是通用的,因为您将实际类的名称作为泛型类型参数。
如果您想要通用参数,请使用通用名称:
interface Function<A,B,C,D>
{
public D apply(A a ,B b , C c);
}
否则,它不必是通用的:
interface Function
{
public returnResult apply(LeadMaster lead,JSONObject jsonObject,String str);
}