forEachの内部に外部接続変数を使用してラムダ

user1578872:

私は一度作成され、forEachの内部で使用された接続オブジェクトを持っています。それはforEachの内部で使用される初期値なしで最終的なものとして、最終的に接続オブジェクトを使用することができません。

final Connection connection;
        try {
            connection = db.createConnection();

            final Map<String, String> dataMap = adminClient.list().values();

            dataMap.entrySet().forEach(entry -> {

                // Need to use connection object here ...
                // Unable to use the connection if it is not final and to make it final, not initializing it to null  ...
            });

        }
        catch (final Exception e) {
            e.printStackTrace();
        }
        finally {
            // Unable to use the connection here if it is not initialized to null ...
            if (connection != null) {
                connection.close();
            }
        }

他のより良い方法はありますか?

ホルガー:

あなたは使用する必要があるのtry-と資源ステートメントのJava 7が存在します。

try(Connection connection = db.createConnection()) {
    final Map<String, String> dataMap = adminClient.list().values();
    dataMap.entrySet().forEach(entry -> {
        // use connection object here ...
    });
 }
 catch (final Exception e) {
    e.printStackTrace(); // replace with real handling later
 }

これは、呼び出す必要がなくなりますのでclose、手動での、あなたが変数をPREINITIALIZEする必要はありませんnullボーナスとして、それはでスローされた例外処理することができclose、正しく方法を。

あなたのクローズ操作がない場合でもAutoClosable.close()、それは容易に適合することができます:

try {
    Connection connection = db.createConnection();
    try(AutoCloseable c = () -> connection.close(timeout)) {
        final Map<String, String> dataMap = adminClient.list().values();
        dataMap.entrySet().forEach(entry -> {
            // use connection object here ...
        });
    }
}
catch (final Exception e) {
    e.printStackTrace(); // replace with real handling later
}

そしてあなたがあなたの元を主張する場合にはfinally、ロジック:

try {
    Connection connection = db.createConnection();
    try {
        final Map<String, String> dataMap = adminClient.list().values();
        dataMap.entrySet().forEach(entry -> {
            // use connection object here ...
        });
    }
    finally {
        if(connection != null) connection.close(timeout);
    }
}
catch (final Exception e) {
    e.printStackTrace(); // replace with real handling later
}

おすすめ

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