1 minute read

static 구조

스크린샷 2020-07-15 오전 11 25 50

static 을 공부하기위해서 짠 샘플 코드 (enum 을 이용해서 user level 을 다루고있다.)

UserLevel

public enum UserLevel {
    BASIC ("BA", "일반회원"),
    GOLD ("GD", "골드회원"),
    PLATINUM ("PL", "플래티넘");

    UserLevel(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    private String code;
    private String desc;

    final static Map<String,UserLevel> map = new HashMap<>();

    static {
        for (UserLevel userLevel : UserLevel.values()) {
            map.put(userLevel.code, userLevel);
        }
    }

    public static UserLevel findByCode(String code) {
        return map.get(code);
    }
}

static 블럭

실행 순서 : 1) 클래스가 로딩된다. 2) 클래스 변수가 있으면 메모리를 생성한다.. 3) static 블록이 선언된 순서대로 실행된다. 최초 한번만 실행할 것이라면 static 으로 간단하고 빠르게 하면된다

    static {
        for (UserLevel userLevel : UserLevel.values()) {
            map.put(userLevel.code, userLevel);
        }
    }

이런 식으로 사용도 되지만 주로 클래스 변수를 초기화 할 때 사용한다.

final static Map<String,UserLevel> map = new HashMap<>();

이것 또한 마찬가지다. 최초 한번만 생성한다.

static method(정적 메소드)

static method 를 사용하는 이유 : static method 를 사용하는 이유는 주로 객체를 생성하지않고도 메소드를 사용할 수 있다.

Math

public final class Math {
    public static double floor(double a) {
        return StrictMath.floor(a); // default impl. delegates to StrictMath
    }
}

이렇게 floor method 는 static method 로 되어있다.

Paging

public class Paging {
    public int getLastPageNo() {
        double temp = (double) this.totalCount / (double) this.pageCountPerBlock;
        return (int) Math.ceil(temp);
    }
}

return (int) Math.ceil(temp); 이 줄을 봤으면 좋겠다! static method 를 활용한 예제다!

주의

정적 메소드에선 정적변수가 아닌 변수를 사용할 수 없습니다 왜냐면 인스턴스에 대한 레퍼런스가 아닌! 클래스에 대해 호출되기 때문입니다.

만약 사용하면 컴파일러는 어떤 인스턴스의 변수인지 몰라서 에러가 발생합니다.

static 변수 (정적 변수)

사용 이유 : static을 사용하여 여러 객체가 하나의 메모리를 참조하도록 하면 메모리 효율이 더욱 높아질 것입니다.

  • PAGE_COUNT_PER_BLOCK 는 결코 변하지 않는 값이므로 final 키워드 를 붙여줍니다.
  • static은 상수의 값을 갖는 경우가 많으므로 public 으로 선언을 하여 사용합니다.

-> public static final int PAGE_COUNT_PER_BLOCK = 10;

@Service
public class StudentServiceImpl implements StudentService {

    public static final int PAGE_COUNT_PER_BLOCK = 10;
    
    @Override
    public ListResponse<StudentDetail> getStudentDetailList(int page, int rows, String sord) {
        long totalCount = studentRepository.findStudentDetailListCount();
        Paging paging = new Paging(PAGE_COUNT_PER_BLOCK, totalCount, rows);
        int start = paging.getStartLimit(page);
        List<StudentDetail> studentDetailList = studentRepository.findStudentDetailList(start, rows, sord);
        return new ListResponse<>(totalCount, paging.getLastPageNo(), studentDetailList);
    }
}

주의깊게 봐야할 코드는

  • public static final int PAGE_COUNT_PER_BLOCK = 10;
  • Paging paging = new Paging(PAGE_COUNT_PER_BLOCK, totalCount, rows);

입니다.

Categories:

Updated: