9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

public static finalを省略する方法

Posted at
public class Constants {
    /** 煩悩の数 **/
    public static final int BONNOU_COUNT = 108;

    /** 四国の霊場の数 **/
    public static final int SHIKOKU_REIJO_COUNT = 88;

    /** 都道府県の数 **/
    public static final int TODOFUKEN_COUNT = 47;
}

このコードのように定数値を1つのクラスにまとめて書く場合、public static finalをいちいち書くのが面倒になります。
省略する方法を2つ紹介します。

■1. Interface化

public interface Constants {
    /** 煩悩の数 **/
    int BONNOU_COUNT = 108;

    /** 四国の霊場の数 **/
    int SHIKOKU_REIJO_COUNT = 88;

    /** 都道府県の数 **/
    int TODOFUKEN_COUNT = 47;
}

classをinterfaceにするだけでpublic static finalがそのまま省略できます。
ただ、暗黙的過ぎて気持ち悪いです。

■2. Lombokの@FieldDefaultsを使う
http://projectlombok.org/features/experimental/FieldDefaults.html

import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;

@FieldDefaults(makeFinal=true, level=AccessLevel.PUBLIC)
public class Constants {
    /** 煩悩の数 **/
    static int BONNOU_COUNT = 108;

    /** 四国の霊場の数 **/
    static int SHIKOKU_REIJO_COUNT = 88;

    /** 都道府県の数 **/
    static int TODOFUKEN_COUNT = 47;
}

publicとfinalを省略できます。
また、protectedなど他のアクセスレベルにも対応できます。

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?