반응형
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 하는 것이 보인다
반응형
'Language > Java' 카테고리의 다른 글
자바 Stream BigDecimal 더하기 빼기 방법 (0) | 2022.12.08 |
---|---|
자바 Stream filter 사용 시 조건(if) 적용방법 (0) | 2022.12.07 |
자바 List 선언과 동시에 초기화하는 방법 (1) | 2022.09.19 |
자바 List<BigDecimal> Stream으로 합계 구하는 방법 (0) | 2022.08.09 |
자바 List<class>를 Page로 Return 하는 방법 (0) | 2022.08.09 |
댓글