How to use javapoet generate java file

import groovy.json.JsonSlurper
import com.squareup.javapoet.TypeSpec
import com.squareup.javapoet.JavaFile

class ConfigPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.afterEvaluate {
            File file = project.file("config.json");
            if (!file.exists()) {
                throw new Exception("config.json not exist!");
            String json = file.text;
            JsonSlurper jsonSlurper = new JsonSlurper();
            def config = (Map<String, Map<String, String>>) jsonSlurper.parseText(json);
            println("read config result is \n $config");
            TypeSpec.Builder builder = TypeSpec.classBuilder("UpConfigData")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            JavaFile javaFile = JavaFile.builder("com.haier.uhome.uplus.plugin.uppermissionplugin.initdemo",
            File createFile = new File(project.projectDir, "src/main/java")
            if (!createFile.exists()) {
            println "[write to]: ${createFile.absolutePath}"

apply plugin: ConfigPlugin

buildscript {
    repositories {
    dependencies {
        classpath 'com.squareup:javapoet:1.12.1'

dependencies {
    implementation 'com.squareup:javapoet:1.12.1'

get the issue:
FAILURE: Build failed with an exception.

  • Where:
    Script ‘/Users/long1/Downloads/InitDemo/app/config.gradle’ line: 18

  • What went wrong:
    A problem occurred configuring project ‘:app’.

No such property: Modifier for class: ConfigPlugin
Caused by: groovy.lang.MissingPropertyException: No such property: Modifier for class: ConfigPlugin

I think you’re just missing an import:

import javax.lang.model.element.Modifier
1 Like

Your efforts were appreciated very much.