一个好用的JAVA工具类 - 条件执行
2022-07-30 本文已影响0人
极简博客
不喜欢写if语句的看过来
/**
* if 语句
* @author Cpz
* @since 2022-07-30
*/
public final class TrueOptional {
private boolean flag;
public static TrueOptional of(Boolean flag) {
TrueOptional trueOptional = new TrueOptional();
trueOptional.flag = Boolean.TRUE.equals(flag);
return trueOptional;
}
public void then(Execute execute) {
if (flag) {
execute.apply();
}
}
@FunctionalInterface
public interface Execute {
void apply();
}
public static void main(String[] args) {
Boolean flag = null;
TrueOptional.of(true).then(() -> System.out.println("true ...."));
TrueOptional.of(false).then(() -> System.out.println("false ...."));
TrueOptional.of(null).then(() -> System.out.println("null ...."));
if (flag) { System.out.println("NPE");}
}
}