妙用Java 8中的 Function接口 消灭if...else(非常新颖的写法)

妙用Java 8中的 Function接口 消灭if...else(非常新颖的写法),第1张

妙用Java 8中的 Function接口 消灭if...else(非常新颖的写法) 妙用Java 8中的 Function接口 消灭if…else(非常新颖的写法)

链接: 参考地址


抛异常接口

@FunctionalInterface
public interface ThrowExceptionFunction {
    
    void throwMessage(String message);
}

If , else 分支 *** 作接口定义

@FunctionalInterface
public interface BranchHandle {
    
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}

工具类实现接口

import org.junit.platform.commons.util.StringUtils;

public class VUtils {

    
    public static ThrowExceptionFunction isTure(boolean b) {

        return (errorMessage) -> {
            if (!b) {
                throw new RuntimeException(errorMessage);
            }
        };
    }

    
    public static BranchHandle isTrueOrFalse(boolean b) {
        return (trueHandle, falseHandle) -> {
            if (b) {
                trueHandle.run();
            } else {
                falseHandle.run();
            }
        };
    }
    
}

测试类调用

public static void main(String[] args) {

        boolean flag = true;
        
        VUtils.isTrueOrFalse(flag)
                .trueOrFalseHandle(
                        () -> {
                            System.out.println("----正常----");
                            System.out.println("接口调用成功!");

                        }, () -> {
                            VUtils.isTure(flag).throwMessage(" *** 作失败,请联系管理员!!");
                        }
                );
    }

-自定义判断是否null值处理

接口定义

import java.util.function.Consumer;


public interface PresentOrElseHandler {

    
    boolean presentOrElseHandle(Consumer action, Runnable emptyAction);
}

工具类调用此方法

null值返回true,否则为false

 
    public static PresentOrElseHandler isBlank(String str) {
        return (consumer, runnable) -> {
            if (StringUtils.isBlank(str)) {
                runnable.run();
                return true;
            } else {
                consumer.accept(str);
                return false;
            }
        };
    }

测试类

public static void main(String[] args) {

        boolean flag = true;

        String str = "";
        VUtils.isTrueOrFalse(VUtils.isBlank(str)
                .presentOrElseHandle(
                        System.out::println, () -> {
                            return;
                        }
                ))
                .trueOrFalseHandle(
                        () -> {
                            System.out.println("----正常----");
                            System.out.println("接口调用成功!");
                        }, () -> {
                            VUtils.isTure(flag).throwMessage(" *** 作失败,请联系管理员!!");
                        }
                );

    }

测试结果

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5582246.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存