Dynamically create tasks for multi java version testing

Hi, I have a project thats compiled under java 8, but i need compile and run the test suite for it under the rest of the LTE java versions. I tried doing it dynamically, but kept running into issues so for the time being, i just created each test compile and test task explicitly. Here’s what i was trying to do originally, just wondering if this is possible at all and i’m just missing something.

val javaTestVersions = listOf(11,17,21)

javaTestVersions.forEach {
    println("curjvm ${it}")
    tasks.register<JavaCompile>("compileTestJava${it}") {
        source = sourceSets["test"].java
        classpath = configurations["java11PlusTestDependencies"]
            .plus(sourceSets["test"].compileClasspath)

        destinationDirectory.set(file("${layout.buildDirectory}/classes/java/testJava${it}"))
        options.compilerArgs.addAll(listOf("--release", "${it}"))
        javaCompiler.set(javaToolchains.compilerFor {
            languageVersion.set(JavaLanguageVersion.of(it))
        })
    }
    tasks.register<Test>("testOnJava${it}") {
        useJUnitPlatform()
        jvmArgs("--add-exports=java.base/sun.security.provider=ALL-UNNAMED",
            "--add-opens=java.base/sun.security.util=ALL-UNNAMED")
        javaLauncher.set(javaToolchains.launcherFor {
            languageVersion.set(JavaLanguageVersion.of(it))
        })
        val curCompile = tasks.named("compileTestJava${it}") as JavaCompile
        testClassesDirs = files(curCompile.get().destinationDirectory)
        classpath = files(curCompile.get().destinationDirectory) +
                configurations["java11PlusTestDependencies"]
                    .plus(configurations.testRuntimeClasspath.get())
                    .plus(sourceSets["main"].output)
        dependsOn(curCompile)


    }
}