LoginSignup
0
0

More than 5 years have passed since last update.

[Java][Spring][thymeleaf]自作Dialectのメソッドにnullが渡されてもエラーにならないようにする

Last updated at Posted at 2019-04-04

前提

  • SpringのプロジェクトでViewテンプレートにthymeleafを使っている
  • 自作のDialectクラスを作っている

現象

サンプルクラス

public class MyDialect {
  public String sampleMethod(Integer number) {
    if (number == null) {
      return "nullだよ";
    }
    return number + "だよ";
  }
}


一見、NULLが来ても問題ないように感じられるが、実際にthymeleafから
<th:block th:text="${#myDialect.sampleMethod(null)}"></th:block>

が呼ばれると、処理がそこに到達する前に IllegalStateException エラーとなる。

自作したDialectクラスのメソッドでは引数にNULLが来る場合は例外エラーとなる。

回避方法

  • null になる可能性のある引数に final をつける
    • 受け取った引数の値の変更はできなくなる
  • null の場合の処理を実装する
public class MyDialect {
  public String sampleMethod(final Integer number) {
    if (number == null) {
      return "nullだよ";
    }
    return number + "だよ";
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0