在构造函数中设置带有反射的final字段



我试图使多个*.properties文件内的消息多语言应用程序。我已经开始这样做了:


public Language(@NotNull Map<String, String> info) {
Validate.notNull(info, "Language information cannot be null");
this.PLUGIN_PREFIX = info.get("PLUGIN_PREFIX");
this.ARGUMENT_CODE = info.get("ARGUMENT_CODE");
// etc...
}

现在,有很多消息,我不想每次都输入相同的内容(加上可能有打字错误,这可能是一个问题…)。

我想到的第一个解决方案是循环遍历所有类似的字段(大写,final,非静态等),然后使用反射使用字段名作为键将其设置为值。显然,编译器不会让我这么做,因为它认为final字段还没有初始化。

像这样:

public Language(@NotNull Map<String, String> info) {
Validate.notNull(info, "Language information cannot be null");
Field[] fields = /* TODO get fields */ new Field[0];

for (Field f : fields) f.set(f.getName(), info.get(f.getName()));
}

是否有一种方法可以工作?还是有更好的解决方案?

编辑:快速命名约定问题,这些最后的"常量"应该是吗?是大写吗?

通常不直接将文本消息存储在常量中,而只是将消息键存储在常量中。然后使用这些键来获取地图中的实际文本消息。

你可以直接使用map,但是在Java中,有ResourceBundle。ResourceBundle可以直接从.properties文件中加载。

my-bundle_en.properties:

my.message=Hello, world!
my-bundle_fr.properties:
my.message=Bonjour tout le monde!

my-bundle_de.properties:

my.message=Hallo Welt!


Something.java:

public static final MY_MESSAGE = "my.message";

ResourceBundle bundle = ResourceBundle.getBundle("my-bundle");
String text = bundle.getMessage(MY_MESSAGE);
System.out.println(text);

最新更新