通常、定数は関連するクラスに属します。例えば:
public class Service {
public static final int PORT = 8080;
public static final int TIMEOUT = 10_000;
public Service() {
// ...
}
}
public class AppWindow {
public static final boolean CENTER_WINDOW = false;
public static final int VISIBLE_LINES = 12;
public AppWindow() {
// ...
}
}
定数を構成可能にしたい場合、最も簡単な方法は、システム プロパティとして定義可能にすることです。
public class Service {
public static final int PORT = Math.max(1,
Integer.getInteger("Service.port", 8080));
public static final int TIMEOUT = Math.max(1,
Integer.getInteger("Service.timeout", 10_000));
}
public class AppWindow {
public static final boolean CENTER_WINDOW =
Boolean.getBoolean("AppWindow.centerWindow");
public static final int VISIBLE_LINES = Math.max(1,
Integer.getInteger("AppWindow.visibleLines", 12));
}
ユーザーがファイルでこれらのデフォルトを構成できるようにしたい場合は、定数を含むクラスのいずれかがロードされる前に行われている限り、プロパティ ファイルからそれらを読み取ることができます。
Path userConfigFile =
Paths.get(System.getProperty("user.home"), "MyApp.properties");
if (Files.isReadable(userConfigFile)) {
Properties userConfig = new Properties();
try (InputStream stream =
new BufferedInputStream(Files.newInputStream(userConfigFile))) {
userConfig.load(stream);
}
Properties systemProperties = System.getProperties();
systemProperties.putAll(userConfig);
System.setProperties(systemProperties);
}
(簡潔にするために、プロパティ ファイルの場所を意図的に単純化しすぎています。各 OS には、そのようなファイルの場所に関する異なるポリシーがあります。)