Last active
October 14, 2020 18:02
-
-
Save JensKnipper/2a267325faad1e3fa4f490d36cb2330a to your computer and use it in GitHub Desktop.
Generatiing Enums with JCodeModel: https://blog.jensknipper.de/blog/generating-enums-in-java-with-jcodemodel/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package de.jensknipper.jcodemodel; | |
import com.helger.jcodemodel.*; | |
import java.io.File; | |
import java.io.IOException; | |
public class EnumGenerator { | |
public static void main(String[] args) throws JCodeModelException, IOException { | |
JCodeModel codeModel = new JCodeModel(); | |
JPackage jPackage = codeModel._package("de.jensknipper.jcodemodel"); | |
JDefinedClass jClass = jPackage._enum("ExampleEnumName"); | |
// DefinedClass jClass = codeModel._class("ExampleEnumName", EClassType.ENUM); // Alternative without package declaration | |
JFieldVar field = jClass.field(JMod.PRIVATE + JMod.FINAL, String.class, "exampleField"); | |
JMethod getterMethod = jClass.method(JMod.PUBLIC, field.type(), "getExampleField"); | |
getterMethod.body()._return(field); | |
JMethod constructor = jClass.constructor(JMod.NONE); | |
JVar constructorParam = constructor.param(String.class, field.name()); | |
constructor.body().assign(JExpr.refthis(field), JExpr.ref(constructorParam)); | |
JEnumConstant jEnum = jClass.enumConstant("ENUM_1"); | |
jEnum.arg((JExpr.lit("enumFieldValue"))); | |
File file = new File("src/main/java"); | |
codeModel.build(file); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment