Java Static Interface Method

By | 2022년 8월 14일
Table of Contents

Java Static Interface Method

Java 8 버전부터 interface 에 static method 를 추가할 수 있게 되었다.

기본 문법

public interface Vehicle {
    static int getHorsePower(int rpm, int torque) {
        return (rpm * torque) / 5252;
    }
}

static method 는 interface 에 직접 속하고,
implement 된 객체에는 속하지 않는다.

Vehicle.getHorsePower(2500, 480));

구체적인 사용예

관련 메소드들을 한 곳에 모아 둘 수 있기 때문에 좋다.

Enum 의 value 를 반환받는 메소드와,
value 로 Enum 을 생성하는 메소드를 한곳에 모아 둘 수 있다.

public interface BaseEnum<V> {

    V getValue();

    static <E extends Enum<E> & BaseEnum<ID>, ID> E fromValue(ID value, Class<E> type) {
        if (value == null) {
            return null;
        }

        for (E e : type.getEnumConstants()) {
            if (e.getValue().equals(value)) {
                return e;
            }
        }

        return null;
    }
}

Enum 의 생성은 Enum 의 타입이 확정된 이후에 가능하다.
아래와 같은 방식으로 Enum 을 생성한다.

public class YNTypeConverter extends BaseEnumConverter<YNType, String> {

    @Override
    public YNType convertToEntityAttribute(String dbData) {
        return BaseEnum.fromValue(dbData, YNType.class);
    }
}

전체 소스는 여기 에서 확인할 수 있다.

답글 남기기