How to create a dynamic Interface with properties file at compile time?

前端 未结 2 1551
执念已碎
执念已碎 2021-01-15 15:46

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 16:37

    I would not generate a class or interface from properties because you would lose the abilities to :

    • document those properties, as they would be represented by a java element + javadocs
    • references those properties in your code, as they would be play old java constant, and the compiler would have full knowledge of them. Refactoring them would also be possible while it would not be possible with automatic names.

    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.

    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:

    • convert the key to a valid java identifier (you can use isJavaIdentifierStart and isJavaIdentifierPart to replace invalid char by a _)
    • write your class/interface/whatever you like using plain old Java (and don't forget to escape for eventual doublequote or backslashes !)

    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.

    Still, I would really don't do that and use a POJO loaded with whatever need (CDI, Spring, Static initialization, etc).

提交回复
热议问题