Use Generic Supplier to throw unchecked excpetion

Chota Bheem :

I have list of methods which has Supplier<T> arguments for returning default values of different types. However, in some cases I need to throw exception(unchecked) instead of values.

Currently, I have to pass the lambda for each function definition but I would like to create supplier instance for throwing the exception and re-use it in all function definition.

I have following code:

    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());
    }

But I am looking to do something like :

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


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

Appreciate any help on this. Thanks.

MikeFHay :

Similar to @jon-hanson's answer, you can define a method which returns the lambda directly, with no cast needed:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72724&siteId=1