带点的Groovy静态方法

时间:2018-07-27 11:42:36

标签: groovy

为什么我的代码有编译错误:

class SomeList {

    final String field

    SomeList(String field) {
        this.field = field
    }

    static SomeList "Regular name of method"() {
        return new SomeList("Regular name of method")
    }

    static SomeList "Name with.dot"() {
        return new SomeList("Name with.dot")
    }
}

class SomeListTests {

    @Test
    def "some list test"() {
        //given
        SomeList list = SomeList()

        //when
        list."Regular name of method"()

        //then
        //compilation error
    }
}

错误消息:

  

错误:Groovyc:编译example-project_test的测试时:错误!源单元“ /home/alex/Projects/example-project/src/test/groovy/SomeListTests.groovy”中“语义分析”阶段的异常”问题加载类SomeList

我在文档中没有找到关于方法名称(字符串)的任何限制。

当我使用GroovyShell创建main方法并尝试使用此方法启动脚本时,它将进行编译。

class Main {
    public static void main(String[] args) {
        GroovyShell shell = new GroovyShell()
        shell.run(new File("path/to/Script.groovy"), Collections.emptyList())
        println "Everything is cool"
    }
}

这是Script.groovy:

SomeList."Regular name of method"()
SomeList."Name with.dot"()

1 个答案:

答案 0 :(得分:0)

我在IDEA中将Test.groovy文件创建为Groovy Script文件

import org.junit.Test

class SomeList {

    final String field

    SomeList(String field) {
        this.field = field
    }

    static SomeList "Regular name of method"() {
        return new SomeList("Regular name of method")
    }

    static SomeList "Name with.dot"() {
        return new SomeList("Name with.dot")
    }
}

class SomeListTests {

    @Test
    void "some list test"() {
        //given
        SomeList list = new SomeList()

        //when
        println list."Regular name of method"()

        //then
        println list."Name with.dot"()
    }
}

对我来说很好。我正在使用Groovy 2.4.15。 输出为:

SomeList@cb51256
SomeList@59906517