gpt4 book ai didi

java - 使用 Generic Supplier 抛出未经检查的异常

转载 作者:搜寻专家 更新时间:2023-11-01 01:20:06 25 4
gpt4 key购买 nike

我有一个方法列表,其中有 Supplier<T>用于返回不同类型的默认值的参数。但是,在某些情况下,我需要抛出异常(未经检查)而不是值。

目前,我必须为每个函数定义传递 lambda,但我想创建供应商实例以抛出异常并在所有函数定义中重新使用它。

我有以下代码:

    public static void main(String[] args)
{

testInt("Key1", 10, () -> 99);
testInt("Key2", -19, () -> 0);
testInt("Key3", null, () -> {
throw new UnsupportedOperationException(); //repetition
});
testBoolean("Key4", true, () -> Boolean.FALSE);
testBoolean("Key5", null, () -> {
throw new UnsupportedOperationException();//repetition
});
}

static void testInt(String key, Integer value, Supplier<Integer> defaultValue)
{
if (value != null)
System.out.printf("Key : %s, Value : %d" + key, value);
else
System.out.printf("Key : %s, Value : %d" + key, defaultValue.get());
}

static void testBoolean(String key, Boolean value, Supplier<Boolean> defaultValue)
{
if (value != null)
System.out.printf("Key : %s, Value : %d" + key, value);
else
System.out.printf("Key : %s, Value : %d" + key, defaultValue.get());
}

但我想做类似的事情:

final static Supplier<?> NO_VALUE_FOUND = () -> {
throw new UnsupportedOperationException();
};


testInt("Key3", null, NO_VALUE_FOUND);
testBoolean("Key5", null,NO_VALUE_FOUND);

感谢对此的任何帮助。谢谢。

最佳答案

与@jon-hanson 的回答类似,您可以定义一个直接返回 lambda 的方法,无需转换:

private <T> Supplier<T> noValueFound() {
return () -> {
throw new UnsupportedOperationException();
};
}

关于java - 使用 Generic Supplier 抛出未经检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54036762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com