【Java】Spring Boot + Thymeleaf + Material Design LiteでWebアプリ〜ブラウザからの入力編〜
mokabuu
mokabuu.com
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | private final static String SQL = "select NEWSONG from BANDSONGS where BANDNAME = ?" ; public String getNewSong(Connection connection, String bandname) throws IOException { checkNull(bandname); try (PreparedStatement preparedStatement = connection.prepareStatement(SQL);) { preparedStatement.setString( 1 , bandname); try (ResultSet resultSet = preparedStatement.executeQuery();) { if (resultSet.next()) { String newSong = resultSet.getString( 1 ); return newSong; } else { return null ; } } } catch (SQLException e) { logger.error( "Failed to get newSong!!" , e); throw new IOException(e); } } private void checkNull(String bandname) { if (bandname == null ) { throw new NullPointerException( "bandname is null!!" ); } } |
本日こんな感じのコードを書いていると
友人が「java.Util.Objects」にいい感じのあるよと教えてくれました。
その名も「requireNonNull」先輩。
この先輩があまりに便利過ぎたので備忘録を書いておきます。
[adsense]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | private final static String SQL = "select NEWSONG from BANDSONGS where BANDNAME = ?" ; public String getNewSong(Connection connection, String bandname) throws IOException { Objects.requireNonNull(bandname, "bandname cannot be null!!" ); try (PreparedStatement preparedStatement = connection.prepareStatement(SQL);) { preparedStatement.setString( 1 , bandname); try (ResultSet resultSet = preparedStatement.executeQuery();) { if (resultSet.next()) { String newSong = resultSet.getString( 1 ); return newSong; } else { return null ; } } } catch (SQLException e) { logger.error( "Failed to get newSong!!" , e); throw new IOException(e); } } |
こんな感じで
java.util.Objectsのクラスを読んでみるとこんな感じのことが書かれていました。
指定されたオブジェクト参照が null でないことを確認し、null の場合はカスタマイズされた NullPointerException をスローします。
便利すぎる!!!!!
これからはnullチェックは全部requireNonNull先輩にお任せしましょう。