yang wang
yang wang

Reputation: 163

groovy call method name contains special character

I'd like to call a method which name contains space in static context, but it do not work. Any suggestions?

class Test2 { 
    void "test"() {
        "test a"()
    }

    void "test a"() { 
        println "test a" 
    } 

    public static void main(String[] args) { 
        def t = new Test2() 
        t."test"() //it works
        t."test a"()  //raise error,  Illegal class name "Test2$test a" in class file Test2$test a 
    } 
} 

G:\tmp\groovy\gp1\src>groovy -version 
Groovy Version: 2.3.2 JVM: 1.7.0_02 Vendor: Oracle Corporation OS: Windows 7 

G:\tmp\groovy\gp1\src>groovy Test2.groovy 
Test1.main 
Caught: java.lang.ClassFormatError: Illegal class name "Test2$test a" in class file Test2$test a 
java.lang.ClassFormatError: Illegal class name "Test2$test a" in class file Test2$test a 
        at Test2.main(Test2.groovy:15) 

Upvotes: 3

Views: 1997

Answers (2)

Will
Will

Reputation: 14539

What about invokeMethod?

class Invokes { 

    def "test a"() { 
        "test a" 
    } 

    static main(args) { 
        def t = new Invokes() 
        assert t.invokeMethod("test a", null) == "test a" 
    } 
} 

Upvotes: 2

Opal
Opal

Reputation: 84844

It will work this way:

class Test2 { 

    void "test a"() { 
        println "test a" 
    } 

    public static void main(String[] args) { 
        def t = new Test2() 
        def v = 'test a'
        t."$v"()
    } 
} 

As described here and here, but no idea why Your example doesn't work.

Upvotes: 3

Related Questions