未チェックexcpetionをスローするように一般的なサプライヤーを使用します

Chota Bheem:

私が持っているメソッドのリスト持っているSupplier<T>さまざまなタイプのデフォルト値を返すための引数を。しかし、いくつかのケースでは、私が代わりに値の例外(チェック)をスローする必要があります。

現在、私は、各関数の定義のためのラムダを渡すために持っていますが、私はそれがすべての関数定義で例外と再利用を投げるためにサプライヤーのインスタンスを作成したいと思います。

私は、コードを次のようしています。

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

この上の任意の助けに感謝。ありがとうございました。

MikeFHay:

JON-ハンソンの答え@と同様に、あなたは不要キャストで、直接ラムダを返すメソッドを定義することができます。

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=183514&siteId=1