본문 바로가기
Language/Java

자바 DTO 클래스 내 모든 변수가 NULL인지 확인방법

by wakestand 2022. 10. 11.
반응형
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.lang.reflect.Field;
import java.math.BigDecimal;

@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
public class TestDto {

    private Long id;
    private BigDecimal value;
    private String memo;

    public boolean isDtoEntireVariableNull() {
        try {
            for (Field f : getClass().getDeclaredFields()) {
                if (f.get(this) != null) {
                    return false;
                }
            }
            return true;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}

 

자바에서 DTO 객체를 받아 사용하던 중

객체 자체가 NULL은 아닌데

클래스 내 모든 변수의 값이 NULL인 경우가 있는데

이걸 메소드 하나로 간단하게 확인해 보려면

 

먼저 DTO 내 메소드를 하나 만든 뒤

Field를 사용해서

각 변수가 NULL이 아닌지 확인하고

 

모든 변수가 NULL 이면 true

하나라도 NULL이 아닌 변수가 있으면

false를 반환하는데

 

TestDto testDto1 = TestDto.builder().build();
TestDto testDto2 = TestDto.builder().memo("").build();

System.out.println(testDto1.isDtoEntireVariableNull());
// true
System.out.println(testDto2.isDtoEntireVariableNull());
// false

 

작성한 메소드를 호출해보면

모든 변수가 NULL일 경우에는 true

하나라도 NULL이 아니면 false를

return 하는 것이 보인다

반응형

댓글