我想以功能性的方式实现这样的目标。有什么帮助吗?
public static Function<String[],Void> validateLength3 = (String[] input) -> {
if(input.length != 3)
throw new Exception("length not equals 3");
}
如果数组 length == 3
,我希望它不会返回任何内容。
Else
抛出异常
。
最佳答案
您的代码有两个问题:
-
Function
的apply()
方法需要一个返回值。 -
Function
的apply()
方法不能抛出已检查的异常。
您可以使用 Consumer<String>
抛出 RuntimeException
相反:
public static Consumer<String[]> validateLength3 =
(String[] input) -> { if(input.length != 3) throw new RuntimeException("length not equals 3");};
关于java - validateOrThrow 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56538204/