NullPointerException(NPE)란?
NullPointerException
(NPE)은 Java에서 null
인 객체를 사용하려 할 때 발생하는 런타임 예외임.
NPE가 발생하는 경우
null
객체의 메서드를 호출할 때String str = null; int length = str.length(); // NPE 발생
null
객체의 필드에 접근할 때class Example { String text; } Example ex = null; System.out.println(ex.text); // NPE 발생
null
인 배열 요소를 사용할 때String[] array = new String[5]; array[0].length(); // NPE 발생
null
이 포함된 리스트나 맵을 사용할 때List<String> list = new ArrayList<>(); list.add(null); System.out.println(list.get(0).length()); // NPE 발생
NPE를 방지하는 방법
null
여부를 먼저 확인하기if (str != null) { System.out.println(str.length()); }
Optional
사용하기 (Java 8 이상)Optional<String> optionalStr = Optional.ofNullable(str); System.out.println(optionalStr.orElse("기본값").length());
Objects.requireNonNull()
사용하기String safeStr = Objects.requireNonNull(str, "문자열이 null이면 안 됨!");
@NotNull
어노테이션 사용하기public void setName(@NotNull String name) { this.name = name; }
결론
NullPointerException
은 흔한 오류지만, null
체크를 철저히 하거나 Optional
을 사용하면 방지할 수 있음.
'Spring' 카테고리의 다른 글
Could not autowire. No beans of 'PasswordEncoder' type found. BCryptPasswordEncoder 빈 주입 오류 간단하게 해결하기 (0) | 2025.02.19 |
---|---|
로깅설정 DEBUG -> INFO 가 필요한 이유 (0) | 2025.02.12 |
@EqualsAndHashCode 사용 시 엔티티 간 무한 루프 발생 가능성에 대한 원인과 해결 (0) | 2025.02.06 |
JPA 엔티티에서 Lombok 사용 시 프록시 초기화 문제 (0) | 2025.02.06 |
Lombok과 JPA 충돌 가능성 & 해결 방법 (0) | 2025.02.06 |