加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

使用java8的lambda作为方法参数以避免冗余

发布时间:2020-12-15 04:21:01 所属栏目:Java 来源:网络整理
导读:我有一个类,有很多像这样的方法(非常简化): public Record[] getRecordForXXX(String username,String param1) throws MyException { User user = getUser(String username); // Always the same MyObject myObj = getMyObject(param1); // Always the same
我有一个类,有很多像这样的方法(非常简化):

public Record[] getRecordForXXX(String username,String param1) throws MyException {
    User user = getUser(String username); // Always the same
    MyObject myObj = getMyObject(param1); // Always the same

    // Here is the only line of code,this is different in any of thoose methods
    Record[] recs = getRecords1(user,myObject); // or getRecords2(user,myObject) ...

    // Handle those records always the same ...
    handleRecords(recs); // Always the same
    return recs; // Always the same
}

有没有办法使用lambdas来避免冗余,如:

public Record[] getRecord(String userName,String param1,XXX method) throws MyException {
        User user = getUser(String username); // Always the same
        MyObject myObj = getMyObject(param1); // Always the same

        // => Call the given 'method' using the parameters user and myObj and returning records

        // Handle those records always the same ...
        handleRecords(recs); // Always the same
        return recs;  // Always the same
   }

我知道,我可以使用某种接口(命令模式)来做到这一点,但我喜欢使用更多功能的方法…… TIA!

解决方法

试试这个,

public Record[] getRecord(String userName,BiFunction<User,MyObject,Record[]> method) throws MyException {
    User user = getUser(String username); // Always the same
    MyObject myObj = getMyObject(param1); // Always the same

    Record[] recs = method.apply(user,myObj);

    // Handle those records always the same ...
    handleRecords(recs); // Always the same
    return recs;  // Always the same
}

您可以按如下方式调用新功能:

yourObject.getRecord(userName,param1,(aUserName,aParam1) -> {
    // do some stuff with aUserName and aParam1
    return aRecordArray;
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读