我有一个 messages.properties 文件,其中包含我的应用程序中使用的所有字符串消息。 我想将这些消息绑定(bind)到 java 类字段并直接在其他类中使用。
不使用 NLS 可以实现这一目标吗?通过javafx中的某种方法?因为我不想在 UI 类中添加 eclipse 依赖项。
最佳答案
Java 提供了开箱即用的属性文件读取功能。您可以根据您的实际用例进行调整。
例如:
public final class Messages {
private Messages() {
loadFile();
}
private static final class ThreadSafeSingleton {
private static final Messages INSTANCE = new Messages();
}
public static Messages getInstance() {
return ThreadSafeSingleton.INSTANCE;
}
private final Properties props = new Properties();
private void loadFile() {
InputStream is = null;
try {
is = new FileInputStream("messages.properties");
props.load(is);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getMessage(String key) {
if (key == null && key.isEmpty()) return "";
return props.getProperty(key);
}
}
编辑
为了像常量一样使用这些值,您几乎需要将所有内容设为静态:
public final class Messages {
private Messages() {} // Not instantiable
private static final Properties props = loadFile(); // Make sure this static field is at the top
public static final String FOO = getMessage("foo");
public static final String BAR = getMessage("bar");
private static Properties loadFile() {
final Properties p = new Properties();
InputStream is = null;
try {
is = new FileInputStream("messages.properties");
p.load(is);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return p;
}
public static String getMessage(String key) {
if (key == null && key.isEmpty()) return "";
return props.getProperty(key);
}
}
再次警告,Properties
字段必须始终是类中声明的最顶层字段,因为类加载器将为所有其值在以下位置计算的静态字段自上而下加载字段运行时(即通过静态方法设置)。
还有一点,此示例不会处理文件不是文件时会发生的情况 - 它只是返回一个没有值的 Properties
。
关于java - 如何在不使用 eclipse.osgi NLS 的情况下绑定(bind) javafx 中的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49124955/