6. 在 Eclipse 中使用 Gradle 的注释处理 (apt)

6. 在 Eclipse 中使用 Gradle 的注释处理 (apt)

6.1. 概览

gradle 插件支持 gradle 的注释处理。它还支持在 Eclipse 和 IntelliJ 中使用此方法。

6.2. Eclipse IDE 中的安装程序

下面的示例描述使用 com.google.auto.value 为数据模型自动生成构建器的 it 使用情况。

调整你的 build.gradle 启用 gradle 插件。

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "net.ltgt.gradle:gradle-apt-plugin:0.13"
  }
}

apply plugin: "net.ltgt.apt-eclipse"
apply plugin: 'java-library'

repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

dependencies {
    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'
}

6.3. 示例: 使用自动值(Auto-value)与 apt 处理(apt-processing)

下面演示了在 Java 项目中 Auto value apt 处理器的用法。

dependencies {
  // more stuff

  // auto-factory contains both annotations and their processor, neither is needed at runtime
  compileOnly "com.google.auto.value:auto-value:1.5"
  apt         "com.google.auto.value:auto-value:1.5"
}

运行 eclipse 任务之后。在 Eclipse IDE 中配置 apt 处理。

import com.google.auto.value.AutoValue;

@AutoValue
abstract class Task {
    static Task create(String summary, String description, int duration) {
        // See "How do I...?" below for nested classes.
        return new AutoValue_Task(summary, description, duration); // generated by the apt processor
      }

      abstract String summary();
      abstract String description();
      abstract int duration();

}

使用:

import org.junit.Test;
import static org.junit.Assert.*;

public class TaskTest {
    @Test public void testSomeLibraryMethod() {
        Task create = Task.create("Learn apt", "Now", 10);
        System.out.println(create);

    }
}

猜你喜欢

转载自blog.csdn.net/scorpio_3715/article/details/81019534