public enum Constants {
PROP1,
PROP2;
private static final String PATH = "/constants.properties";
private static final Logger logger = LoggerFactory.getLogger(Constants.class);
private static Properties properties;
private String value;
private void init() {
if (properties == null) {
properties = new Properties();
try {
properties.load(Constants.class.getResourceAsStream(PATH));
}
catch (Exception e) {
logger.error("Unable to load " + PATH + " file from classpath.", e);
System.exit(1);
}
}
value = (String) properties.get(this.toString());
}
public String getValue() {
if (value == null) {
init();
}
return value;
}
}
现在,您还需要一个属性文件(我经常将其放在src中,因此将其打包到JAR中),其属性与在枚举中使用的一样。例如:
constants.properties:
#This is property file...
PROP1=some text
PROP2=some other text
现在,我经常在要使用常量的类中使用静态导入:
import static com.some.package.Constants.*;
以及示例用法
System.out.println(PROP1);