如何在编译时使用属性文件创建动态接口? [英] How to create a dynamic Interface with properties file at compile time?
问题描述
这里的问题是,我们使用的属性文件的名称疯狂地巨大,因此我们大多数人都遇到了不正确的密钥命名问题.所以这让我开始思考是否有一种方法可以基于属性文件生成以下接口.我们对属性文件所做的每次更改都会自动调整属性"界面.还是有其他解决方案?
The problem here is that the property file we use has insanely huge name as the key and most of us run into incorrect key naming issues . so it got me thinking if there's a way to generate the following interface based on the property file. Every change we make to the property file will auto-adjust the Properties interface. Or is there other solution?
属性文件
A=Apple
B=Bannana
C=Cherry
应生成以下接口
interface Properties{
public static final String A = "A" // keys
public static final String B = "B";
public static final String C = "C";
}
所以在我的应用程序代码中
So in my application code
String a_value = PROP.getString(Properties.A);
推荐答案
我不会从属性生成类或接口,因为您会失去以下能力:
I would not generate a class or interface from properties because you would lose the abilities to :
- 记录这些属性,因为它们将由一个Java元素+ javadocs 表示
- 在您的代码中引用这些属性,因为它们将充当旧的Java常量,并且编译器将完全了解它们.重构它们也是可能的,而使用自动名称则是不可能的.
您还可以使用枚举,或创建一些特殊的 Property
类,其名称为only和final字段.然后,您只需要一个 get
方法,该方法将使用一个 Properties
,一个 Map
或其他任何方法.
You can also use enums, or create some special Property
class, with a name as only and final field. Then, you only need a get
method that would take a Properties
, a Map
or whatever.
对于您的请求,您可以使用 maven-exec-plugin .
As for your request, you can execute code with the maven-exec-plugin.
您应该简单地创建一个主文件,该主文件将读取您的属性文件以及每个键:
You should simply create a main that would read your properties file, and for each keys:
- 将密钥转换为有效的Java标识符(您可以使用 isJavaIdentifierPart 将无效字符替换为
_
) - 使用普通的旧Java编写类/接口/任何您喜欢的内容(并且不要忘记转义以获取双引号或反斜杠!)
由于这将是您构建的一部分,例如,在构建其他依赖于这些常量的类之前,我建议您创建一个特定的Maven项目以隔离这些构建.
Since it would be a part of your build, say before building other classes that would depends on those constants, I would recommend you to create a specific maven project to isolate those build.
仍然,我真的不会这样做,而是使用随需加载的POJO(CDI,Spring,静态初始化等).
Still, I would really don't do that and use a POJO loaded with whatever need (CDI, Spring, Static initialization, etc).
这篇关于如何在编译时使用属性文件创建动态接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!