Java validateOrThrow实现
我想以一种实用的方式实现类似的功能。有什么帮助吗Java validateOrThrow实现,java,functional-programming,Java,Functional Programming,我想以一种实用的方式实现类似的功能。有什么帮助吗 public static Function<String[],Void> validateLength3 = (String[] input) -> { if(input.length != 3) throw new Exception("length not equals 3"); } 公共静态函数validateLength3=(字符串[]输入)->{ 如果(input.length!=3) 抛出新
public static Function<String[],Void> validateLength3 = (String[] input) -> {
if(input.length != 3)
throw new Exception("length not equals 3");
}
公共静态函数validateLength3=(字符串[]输入)->{
如果(input.length!=3)
抛出新异常(“长度不等于3”);
}
如果arraylength==3,我希望它不会返回任何内容
Else
抛出一个异常
您的代码有两个问题:
函数的apply()
方法需要返回值
函数的apply()
方法无法引发选中的异常
您可以使用一个使用者
,它抛出一个运行时异常
:
public static Consumer<String[]> validateLength3 =
(String[] input) -> { if(input.length != 3) throw new RuntimeException("length not equals 3");};
公共静态使用者验证长度3=
(字符串[]输入)->{if(input.length!=3)抛出新的RuntimeException(“长度不等于3”);};
为什么需要单独的函数进行验证。在流行的库中有一些助手类,它们已经完成了您所需要的工作
即谷歌番石榴
你可以这样写
Preconditions.checkState(input.length == 3, "length not equals 3");
函数
不允许抛出任何选中的异常,请为此定义自定义接口。