Gradle配置用高版本jdk源代码编译成低版本字节码

53 阅读1分钟

关键在于配置sourceCompatibilitytargetCompatibility以及compilerArgs

build.gradle配置如下

plugins {
    id 'idea'
}

group = 'local'
version = '0.0.1-SNAPSHOT'
description = 'Demo'

idea{
    project {
        jdkName = '25'
    }
    module{
        downloadJavadoc = false
        downloadSources = false
    }
}


java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(25)
		// 设置源码版本
        sourceCompatibility = JavaVersion.VERSION_24
		// 设置编译目标版本
        targetCompatibility = JavaVersion.VERSION_24
    }
}

repositories {
    mavenCentral()
}

dependencies {
}

tasks.withType(JavaCompile).configureEach {
    // 方案 A:使用 --release 参数 (推荐,更安全)
    // 这会限制生成的字节码版本为 24,并限制使用的 API 为 24 的 API
    options.compilerArgs += ["--release", "24"]

    // 方案 B:如果你需要更细粒度的控制(源是25,目标是24),可以使用以下参数代替上面的 --release
    // 注意:在某些高版本 JDK 上,仅设置 -target 可能不够,推荐优先使用 --release
    // options.compilerArgs += ["-source", "25", "-target", "24"]
}