Backend/Java

[Lombok] is prefix로 이름 붙인 boolean get 오류 해결하기

Yaerhee 2022. 6. 10. 20:11

문제 내용: DTO의 boolean 이 import 되지 않아 T/F 값을 활용할 수 없음

해결 방법: boolean -> Boolean 으로 타입 변경, is prefix를 제거하는 방향으로 변수 이름 변경


오류 상황

PTableDto.java 안에 정의한 $Execution class 를 활용하려고 하였다.

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Execution {
        private int id;
        private String execPlanId;
        private int rulesIdCount;
        private int tableNameCount;
        private int columnIdCount;
        private String execPlanName;
        private String execTargetRulesId;
        private String execApproach;
        private Double calPortion;
        private LocalDateTime execDate;
        private LocalDateTime execEndDate;
        private String executedBy;
        private boolean isImmediate;
        private String execStatus;
        private int duration;
        private Double errRate;
        private int execCycle;
        private boolean isTempDiag; // <- 요기요
    }
@Override
    public void doExecution(PTableDto.Execution execution) {
    	.... (중간 코드 생략)
    	// result 에서 결과 리포트 시 해당 수치 export
        if (!execution.isTempDiag()) {
            pTableMapper.updateExecutionPlanAfterDiag(execution.getExecPlanId());
        }
        pTableMapper.updateExecution(testResult);
   	}

PTableDto의 boolean isTempDiag을 import 해서, 임시 진단일 경우에는 pTableMapper 일부를 생략하고 넘어가도록 설계했었다.

우선 위의 코드인 상태에서, front 에서 isTempDiag 를 true로 넘긴 후 => URI 로 데이터를 execution 에 받아 왔는데...

얼레? (...) isTempDiag이 false다...

혹시나 모르니 프론트 쪽을 다시 살펴보았는데, 정상적으로 isTempDiag을 true로 내보내고 있었다.

 

Lombok 설정이 잘못되진 않았고, 오류 원인이 더 이상 추측이 되지 않아 검색을 해 보았다.


오류 원인?

 

결론으로는

1. Type 이 boolean이고

2. 변수 이름이 is로 시작될 경우

Lombok 에서의 자동 변환이 원활하게 돌아가지 않을 수 있다.

 

아래의 foo class를 통해 살펴보면,

Lombok의 기본 @Getter, @Setter 활용 시에 boolean isTempDiag을 선언할 경우

setter에는 문제가 없지만, getter에서 is + isTempDiag 때문에 is가 충돌된 것을 볼 수 있다.

    @Getter
    @Setter
    public static class foo {
        private boolean isTempDiag;

        public void foooo() {
            this.setTempDiag(true);
            this.isTempDiag(); // isisTempDiag?!
        }
    }

boolean 타입의 is.. 변수를 설정할 경우 getter인 is... method 출력

(기본 "boolean" 타입에서 Getter/ Setter 를 설정할 때,

변수 이름 앞에서 is가 있을 경우 해당 is가 들어가 있는 getter, setter를 만들어낸다)

이런 경우에는 의도된 바 대로 boolean 값을 가져와 쓰는 것이 불가능하다.

 


 

그렇다면, 위의 결론에 있던 조건을 바꾸어서 foo class의 변수를 다시 호출해 보자.

 

오류 해결하기

 

1. Type 이 boolean이었으니 -> Boolean 으로 변경해서 해결 (일반 getter/setter와 같은 방식의 메소드 선언)

    @Getter
    @Setter
    public static class foo {
        private Boolean isTempDiag;

        public void foooo() {
            this.setIsTempDiag(true);
            // this.isTempDiag(); // Boolean 으로 변경하면서 올바르지 않게 된 표현
            this.getIsTempDiag();
        }
    }

Boolean 타입으로 변수를 선언하면, 기존의 다른 타입과 같은 방식으로 set[변수이름] / get[변수이름] 메소드를 활용할 수 있다.

(.setIsTempDiag() / getIsTempDiag())

 

 

2. 변수 이름이 is로 시작했었으니 -> is로 시작되지 않도록 변수 이름을 바꿔서 해결

boolean isTempDiag 을 => boolean tempDiagYn 으로 변경하고,

조건절에 있던 isTempDiag()을 isTempDiagYn()으로 변경하였다.

private boolean tempDiagYn;
        // result 에서 결과 리포트 시 해당 수치 export
        if (!execution.isTempDiagYn()) {
            pTableMapper.updateExecutionPlanAfterDiag(execution.getExecPlanId());
        }

디버깅을 해보니 아래와 같이 값이 잘 연동되어 출력된다.

 

(p.s.: isImmediate 도 같은 방식으로 해결했습니다. 고치기 전의 기록이니 너무 불-편해 하지 않으셔도 됩니다. (...))

 

문제 해결!

 


추가 사항

 

 

1. boolean, Boolean 두 방식의 차이점

boolean 은 primitive type 이라 메모리 소비가 적으나, T/F 로만 데이터를 출력할 수 있으며

Boolean 은 object wrapper로 단순 T/F 가 아닌 null도 범주에 포함이 가능하다. method가 boolean에 비해 다양하다.

(+ Boolean.valueOf("true")와 같은 방식으로도 활용 가능하고, lazy loading 에도 유용하게 쓰임)

 

2. 변수명에 상관없이 is 접두어를 붙이지 않도록 하는 방법 +@

src/main/java 폴더 내에 아래와 같은 lombok.config 파일을 생성하고,

활용할 attribute를 정의해 주면 된다.

 

noisprefix: 앞에 is를 붙이지 않을지 설정 (기본 false)

accessors.fluent: 메소드 앞에 get, set 등을 붙이지 않을지 설정 (기본 false)

# boolean getter/setter 활용 시 is[...]가 아닌 get/set[...]로 활용
# default value = false
lombok.getter.noisprefix = true

# get, is, set ... 을 접두어로 붙이지 않고
# 변수 이름과 동일한 이름으로 getter / setter 를 설정한다
# default value = false
lombok.accessors.fluent = true
# ex. yaerhee로 이름을 설정 => yaerhee() 로 접근

Lombok의 기본적인 메소드 / 활용 방식을 바꾸고자 한다면 config를 수정해도 좋을 것 같다.

 


출처

https://ratseno.tistory.com/101

 

[Lombok]"is"prefix가 붙은 boolean, Boolean

어노테이션만 붙이면 자동으로 getter, setter, 생성자 등등 여러 가지를 생성해주는 Lombok을 자주 사용합니다. IDE에서 자동생성으로 작성하는 경우도 있지만, 개발 편의성을 위해 Lombok을 쓰는 편입

ratseno.tistory.com

https://www.sololearn.com/Discuss/128675/what-different-between-boolean-and-boolean-in-java

 

What different between Boolean and boolean in Java?

Check out what Mahmood Ali has posted on SoloLearn

www.sololearn.com

https://blog.hexabrain.net/398?category=431864 

 

프로젝트 롬복(Project Lombok) 살펴보기

프로젝트 롬복(Lombok) 프로젝트 롬복(Project Lombok, 이하 롬복)은 게터(getter), 세터(setter), equals()/hashCode() 등과 같이 코드를 작성하면서 계속 비슷한 내용이 지루하게 반복되었던 코드들을 애노테이.

blog.hexabrain.net