[자바] autoboxing 실수 (실 사례)
자바에 primtive 타입에서 클래스 타입이 들어오면서 (int->Integer, boolean ->Boolean등)
좋아지는 부분도 있지만, 개발자들이 실수하는 코드도 있다.
특히 자바가 아닌 다른 언어에서는 자동으로 지원하지만, 자바는 되지 않는 것들이 바로 이런 경우일 것이다.
자바에서는 boolean 값에 null을 넣을 수 없다. (type mismatch)
boolean a = null;
하지만 아래 boolean과 Boolean을 동시에 사용하면, Boolean으로 변환(autoboxing)이 된다.
다른 언어에서처럼 null에 대해서는 특별히 처리가 안되는 부분이 있다.
코드
@Test
public void test() {
boolean debug = isDebug();
System.out.println(debug);
}
public Boolean isDebug() {
return null;
}
결과
메소드의 리턴 결과에 Boolean 변수를 null을 리턴하면, NPE가 발생한다.
자바에 익숙치 않은 다른 언어 개발자는 null 을 사용하는 경향이 있는 것은
if 문이 숫자 또는 null 에 대한 처리를 하기 때문인 듯하다.
java language spec에 따르면, if문은 반드시 boolean이나 Boolean 이어야 한다.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.9
14.9. The if
Statement
The if
statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.
The Expression must have type boolean
or Boolean
, or a compile-time error occurs.