简体   繁体   中英

generate javascript from java class as a maven build step

I have a java enum that is used in my web application. I also have a lot of javascript code that refers to the values of the enum. It would be ideal If I could generate a javascript file from the enum as part of the maven build process. Does anyone know of a project that solves this problem or of an elegant way to tackle it ? Thanks!

It turns out that there is a great way to do it using a groovy maven plugin as a "prepare-package" phase. This is the code : In your pom.xml add this entry :

<plugin>
                <groupId>org.codehaus.groovy.maven</groupId>
                <artifactId>gmaven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>script-prepare-package1</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <source>${basedir}/src/main/groovy/GenerateJavaScriptEnum.groovy</source>
                        </configuration>
                    </execution>

                </executions>
            </plugin>

This is how the groovy script, GenerateJavaScriptEnum.groovy, looks like :

    def fields = []


com.foo.bar.YourEnum.values().each() { f->
    fields << "${f.name()} : \"${f.getId()}\""
}

if (fields) {
    log.info("Generating Javascript for com.foo.bar.YourEnum")

    [
            new File("${project.build.directory}/${project.build.finalName}/js"),
            new File("${project.basedir}/src/main/webapp/js")
    ].each() { baseOutputDir->
        if (!baseOutputDir.exists()) {
            baseOutputDir.mkdirs()
            log.info("Created output dir ${baseOutputDir}")
        }

        def outfile = new File(baseOutputDir, "YourEnum.js")

        log.info("Generating ${outfile}")

        def writer = outfile.newWriter("UTF-8")
        writer << "// FILE IS GENERATED FROM com.foo.bar.YourEnum.java.\n"
        writer << "// DO NOT EDIT IT.  CHANGES WILL BE OVERWRITTEN BY THE BUILD.\n"
        writer << "YourEnum = {\n"
        writer << fields.join(",\n")
        writer << "\n}"
        writer.close()
    }
}

I had the same problem and ended up creating a custom tag that would allow me to iterate over the enum in my jsp,

public static Enum<?>[] getValues(String klass) {
    try {
        Method m = Class.forName(klass).getMethod("values", (Class<?>[]) null);
        Object obj = m.invoke(null, (Object[]) null);
        return (Enum<?>[]) obj;
    } catch (Exception ex) {
        return null;
    }
}

Then in my jsp I just do,

var MyEnum = [
<c:forEach var="type" items="${foocustomtags:enumiter('com.foo.MyEnum')}">
  '${type.value}': '${type.text}',
</c:forEach>
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM