LoginSignup
0
2

More than 5 years have passed since last update.

getAttribute()とアンボクシング

Last updated at Posted at 2017-10-21

Servletをやっていて、つい

HttpSession session = request.getSession();
boolean hasError = (Boolean)session.getAttribute("hasError");

というコードを書いてしまった。結果、これはNullPointerExceptionを投げてきた。

getAttribute()は戻り値がObject型なので、ラッパークラス(ここではBoolean)でキャストする必要がある。
ところが、最初にgetAttribute()を呼び出した時、戻り値はnullになるので、Boolean型のnullをアンボクシングしてboolean型に代入しようとした結果、NullPointerExceptionになる、という仕組みなのだった。

アンボクシングが起きる際、nullに気をつけるべきだったが、ちょっとこれは個人的に想定外だったので、一応メモをしておく。

0
2
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
2