No-arg 编译器插件

The no-arg compiler plugin generates an additional zero-argument constructor for classes with a specific annotation.

The generated constructor is synthetic, so it can’t be directly called from Java or Kotlin, but it can be called using reflection.

This allows the Java Persistence API (JPA) to instantiate a class although it doesn’t have the zero-parameter constructor from Kotlin or Java point of view (see the description of kotlin-jpa plugin below).

In your Kotlin file

Add new annotations to mark the code that needs a zero-argument constructor:

  1. package com.my
  2. annotation class Annotation

Gradle

Add the plugin using Gradle’s plugins DSL:

【Kotlin】

  1. plugins {
  2. kotlin("plugin.noarg") version "1.9.10"
  3. }

【Groovy】

  1. plugins {
  2. id "org.jetbrains.kotlin.plugin.noarg" version "1.9.10"
  3. }

Then specify the list of no-arg annotations that must lead to generating a no-arg constructor for the annotated classes:

  1. noArg {
  2. annotation("com.my.Annotation")
  3. }

Enable invokeInitializers option if you want the plugin to run the initialization logic from the synthetic constructor. By default, it is disabled.

  1. noArg {
  2. invokeInitializers = true
  3. }

Maven

  1. <plugin>
  2. <artifactId>kotlin-maven-plugin</artifactId>
  3. <groupId>org.jetbrains.kotlin</groupId>
  4. <version>${kotlin.version}</version>
  5. <configuration>
  6. <compilerPlugins>
  7. <!-- Or "jpa" for JPA support -->
  8. <plugin>no-arg</plugin>
  9. </compilerPlugins>
  10. <pluginOptions>
  11. <option>no-arg:annotation=com.my.Annotation</option>
  12. <!-- Call instance initializers in the synthetic constructor -->
  13. <!-- <option>no-arg:invokeInitializers=true</option> -->
  14. </pluginOptions>
  15. </configuration>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.jetbrains.kotlin</groupId>
  19. <artifactId>kotlin-maven-noarg</artifactId>
  20. <version>${kotlin.version}</version>
  21. </dependency>
  22. </dependencies>
  23. </plugin>

JPA 支持

As with the kotlin-spring plugin wrapped on top of all-open, kotlin-jpa is wrapped on top of no-arg. The plugin specifies @Entity, @Embeddable, and @MappedSuperclass no-arg annotations automatically.

Add the plugin using the Gradle plugins DSL:

【Kotlin】

  1. plugins {
  2. kotlin("plugin.jpa") version "1.9.10"
  3. }

【Groovy】

  1. plugins {
  2. id "org.jetbrains.kotlin.plugin.jpa" version "1.9.10"
  3. }

In Maven, enable the jpa plugin:

  1. <compilerPlugins>
  2. <plugin>jpa</plugin>
  3. </compilerPlugins>

命令行编译器

Add the plugin JAR file to the compiler plugin classpath and specify annotations or presets:

  1. -Xplugin=$KOTLIN_HOME/lib/noarg-compiler-plugin.jar
  2. -P plugin:org.jetbrains.kotlin.noarg:annotation=com.my.Annotation
  3. -P plugin:org.jetbrains.kotlin.noarg:preset=jpa