关于编程有一条古老的规则,而不仅仅是关于它,如果某些东西看起来很漂亮,那么它很可能是正确的做法。
在我看来,这种方法看起来不太好。
第一件事:
不要在接口中声明常量。它违反了封装方法。请查看这篇文章: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_C, key_B, key_A]
它是返回数组的字符串表示,带有特殊的键名。
根据您的要求更改此代码。