【问题标题】:Gradle builds successfully without SourceSet, but fails with SourceSet, Error Cannot Find SymbolGradle 在没有 SourceSet 的情况下成功构建,但使用 SourceSet 失败,错误找不到符号
【发布时间】:2020-12-17 20:13:10
【问题描述】:

我有一个非常简单的 HelloWorld 程序,如果我不使用 Gradle SourceSet,它就可以工作,但如果我这样做,它就会失败。我不明白为什么。请帮忙。

使用 Gradle 6.6.1-bin。我自己手动安装的,只是为了确保它兼容。

问题是,如果我将 build.gradle 文件和 HelloWorld.java 文件放在同一个基目录中,一切都会编译并构建成功。示例命令:

gradle clean build

HelloWorld.java:

package hello;

import org.joda.time.LocalTime;

public class HelloWorld {
  public static void main(String[] args) {
    LocalTime currentTime = new LocalTime();
    System.out.println("The current local time is: " + currentTime);

    Greeter greeter = new Greeter();
    System.out.println(greeter.sayHello());
  }
}

build.gradle SourceSet:

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

repositories {
    mavenCentral()
}

jar {
    archiveBaseName = 'gs-gradle'
    archiveVersion =  '0.1.0'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    implementation "joda-time:joda-time:2.2"
    testImplementation "junit:junit:4.12"
}

但是,如果我尝试将源文件移动到文件夹布局(正如 Gradle 指南所建议的那样是他们的标准)并添加 SourceSet,它会失败。

文件夹布局是这样的:

  • /opt/myProject/src/main/java/HelloWorld.java
  • /opt/myProject/build.gradle

修改 build.gradle with SourceSet:

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'


sourceSets {
    main {
        java {
            srcDir 'src'
        }
    }
}

mainClassName = 'hello.HelloWorld'

repositories {
    mavenCentral()
}

jar {
    archiveBaseName = 'gs-gradle'
    archiveVersion =  '0.1.0'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    implementation "joda-time:joda-time:2.2"
    testImplementation "junit:junit:4.12"
}

现在运行失败:

gradle clean build

控制台输出:

> Task :compileJava FAILED
/opt/myProject/src/main/java/HelloWorld.java:10: error: cannot find symbol
    Greeter greeter = new Greeter();
    ^
  symbol:   class Greeter
  location: class HelloWorld
/opt/myProject/src/main/java/HelloWorld.java:10: error: cannot find symbol
    Greeter greeter = new Greeter();
                          ^
  symbol:   class Greeter
  location: class HelloWorld
2 errors

FAILURE: Build failed with an exception.

我不知道为什么这不起作用。

【问题讨论】:

  • 只需从第二个build.gradle 脚本中删除sourceSets 块:默认情况下,Gradle 将使用src/main/java 作为main sourceSet 的基本目录。你为什么要强制这个目录到src/(你已经按预期将你的sourceFile移动到src/main/java下)
  • @M.Ricciuti 谢谢。我不敢相信这一直是问题所在。我希望 Gradle 及其示例的文档能够更好一些!

标签: java gradle build


【解决方案1】:

正如@M.Ricciuti 指出的那样,我只需要从第二个 build.gradle 脚本中删除 sourceSets 块。默认情况下,Gradle 将使用 src/main/java 作为主 sourceSet 的基本目录,而不需要显式声明它。 (我不知道这一点。)

【讨论】:

    猜你喜欢
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多