这里的问题是我们使用的属性文件作为 key 的名称非常大,我们大多数人都会遇到不正确的 key 命名问题。所以这让我思考是否有一种方法可以根据属性文件生成以下接口(interface)。我们对属性文件所做的每次更改都会自动调整属性界面。或者还有其他解决方案吗?
属性文件
A=Apple
B=Bannana
C=Cherry
应该生成以下接口(interface)
interface Properties{
public static final String A = "A" // keys
public static final String B = "B";
public static final String C = "C";
}
所以在我的应用程序代码中
String a_value = PROP.getString(Properties.A);
最佳答案
关于编程有一条古老的规则,而不仅仅是编程,如果某件事看起来很漂亮,那么很可能它就是正确的做法。
从我的角度来看,这种方法看起来不太好。
第一件事:
不要在接口(interface)中声明常量。它违反了封装方法。请查看这篇文章:http://en.wikipedia.org/wiki/Constant_interface
第二件事:
使用前缀作为属性的名称部分,这些属性在某种程度上特殊,比方说:key_
当您加载属性文件时,迭代键并提取名称以 key_
开头的键,并按照您计划在问题中使用这些常量的方式使用这些键的值。
更新
假设,我们使用 Apache Ant 脚本在编译过程中生成一个巨大的属性文件。
例如,让我们的属性文件 (myapp.properties
) 如下所示:
key_A = Apple
key_B = Banana
key_C = Cherry
anotherPropertyKey1 = blablabla1
anotherPropertyKey2 = blablabla2
我们想要处理的特殊属性的键名称以key_
前缀开头。
因此,我们编写以下代码(请注意,它没有经过优化,只是概念验证):
package propertiestest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
public class PropertiesTest {
public static void main(String[] args) throws IOException {
final String PROPERTIES_FILENAME = "myapp.properties";
SpecialPropertyKeysStore spkStore =
new SpecialPropertyKeysStore(PROPERTIES_FILENAME);
System.out.println(Arrays.toString(spkStore.getKeysArray()));
}
}
class SpecialPropertyKeysStore {
private final Set<String> keys;
public SpecialPropertyKeysStore(String propertiesFileName)
throws FileNotFoundException, IOException {
// prefix of name of a special property key
final String KEY_PREFIX = "key_";
Properties propertiesHandler = new Properties();
keys = new HashSet<>();
try (InputStream input = new FileInputStream(propertiesFileName)) {
propertiesHandler.load(input);
Enumeration<?> enumeration = propertiesHandler.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
if (key.startsWith(KEY_PREFIX)) {
keys.add(key);
}
}
}
}
public boolean isKeyPresent(String keyName) {
return keys.contains(keyName);
}
public String[] getKeysArray() {
String[] strTypeParam = new String[0];
return keys.toArray(strTypeParam);
}
}
类SpecialPropertyKeysStore
过滤并将所有特殊键收集到其实例中。
您可以获取这些 key 的数组,或者检查 key 是否存在。
如果运行此代码,您将得到:
[key_C, key_B, key_A]
它是具有特殊键名称的返回数组的字符串表示形式。
根据需要更改此代码以满足您的要求。
关于java - 如何在编译时使用属性文件创建动态接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25377900/