如何在2.1级的Java项目中添加源代码集



如何在2.1级中向Java项目添加源代码集?

我已经阅读了关于Java插件和SourceSetOutput以及其他一些SO线程的文档,我仍然在努力弄清楚它是如何工作的。

我创建了一个简单的构建脚本来测试我的理解能力。根据《用户指南》第23.7.2节,示例23.5,我似乎可以通过以下操作创建sourceSet:

sourceSets {
   generated
}

在第23.4。项目布局似乎意味着这就是我所需要做的,因为我的源代码集遵循渐变约定。要包含在源集中的代码位于src/generated/java/packagename中。并且将自动添加到类路径中。基于我从使用生成的源集中定义的代码的代码中得到的未找到符号的错误,我认为这是不正确的,需要做其他事情。我需要做什么?

这是我的设置:

build.gradle

apply plugin: 'java'
apply plugin: 'application'
mainClassName = "tester.Test"
sourceSets {
    generated
}

文件结构

tester/
├── build
│   ├── classes
│   │   └── main
│   ├── dependency-cache
│   └── tmp
│       └── compileJava
├── build.gradle
└── src
    ├── generated
    │   └── java
    │       └── tester
    │           └── Boom.java
    └── main
        └── java
            └── tester
                └── Test.java

Boom.java

package tester;
class Boom {
   String sound;
   public Boom (String s){
      sound = s;
   }
}

Test.java

package tester;
class Test {
   public static void main(String[] args) {
      Boom b = new Boom("KABOOM");
      System.out.println("I've run");
      System.out.println(b.sound);
   }
}

您需要按照以下方式修改build.gradle

sourceSets {
    generated
    main {
        compileClasspath += generated.output  // adds the sourceSet to the compileClassPath
        runtimeClasspath += generated.output  // adds the sourceSet to the runtimeClasspath
    }
}
project.run.classpath += sourceSets.generated.output //add the sourceSet to project class path

请记住,添加新的源集与在类路径中编译源集不同。

源集合下面的行是run任务工作所必需的。

最新更新