简体   繁体   English

无法从 .java 类访问带有参数的 @Immutable 类的构造函数

[英]Constructor of @Immutable class with parameters is not accessible from .java classes

I clean generated .class files, and re-build my app.我清理生成的 .class 文件,并重新构建我的应用程序。 If the first call to generated AST constructor happens from a .java class, I get an error.如果对生成的 AST 构造函数的第一次调用发生在 .java 类中,我会收到错误消息。 But if I call a constructor generated by an @Immutable annotation in a .groovy class first, it becomes visible to .java classes since bytecode is already generated and no errors occur.但是,如果我首先在 .groovy 类中调用由@Immutable注释生成的构造函数,它对 .java 类变得可见,因为字节码已经生成并且不会发生错误。

So I am wondering how do I set up gradle so it compiles all groovy classes with needed AST transformations first , so i can use it from .java classes properly?所以,我想知道我怎么设置gradle这个所以编译所有的Groovy类与所需的AST转换第一,这样我就可以从的.java类正确地使用它? Also, how do I use @Builder -generated code from .java classes, since javac doesn't see any ClassName.bulder() method?另外,由于 javac 没有看到任何ClassName.bulder()方法,我如何使用@Builder生成的代码从 .java 类?

  1. Here is my .groovy class with ASTT这是我使用 ASTT 的 .groovy 类

    @Immutable class A { String a; }
  2. Here is how I call its constructor from .java class这是我如何从 .java 类调用它的构造函数

    public class Test { A b = new A("321"); }
  3. And the error I get:我得到的错误:

    Error: "constructor in class [skipped] cannot be applied to given types; required: no arguments found: [skipped] reason: actual and formal argument lists differ in length".错误:“类 [跳过] 中的构造函数不能应用于给定类型;必需:找不到参数:[跳过] 原因:实际和形式参数列表的长度不同”。

I am using Intellij IDEA 14.4 and Gradle to build.我使用 Intellij IDEA 14.4 和 Gradle 来构建。

I had a similar problem once.我曾经遇到过类似的问题。 What worked for me was preventing Java to run before Groovy by setting its source sets in build.gradle to an empty list (see code below).对我有用的是通过将 build.gradle 中的源集设置为空列表来阻止 Java 在 Groovy 之前运行(请参阅下面的代码)。

As far as I understood, this way the Groovy compiler will delegate the Java files to Java, but will do that in the correct order.据我所知,这样 Groovy 编译器会将 Java 文件委托给 Java,但会以正确的顺序进行。 The Java compile on the other hand will ignore Groovy files, which leads to the unfulfilled dependency you are seeing.另一方面,Java 编译将忽略 Groovy 文件,这会导致您看到的未满足的依赖项。

plugins {
    id 'groovy'
    id 'java'
}

sourceCompatibility = 11

sourceSets {
    main {
        java {
            srcDirs = [] // don't compile Java code twice
        }
        groovy {
            srcDirs += 'src/main/java'
        }
    }
}

// …

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM