在Groovy @CompileStatic批注的匿名类中是否有任何方式可以使用ues覆盖方法

时间:2014-06-20 06:22:11

标签: groovy

在Groovy @CompileStatic注释的匿名类中是否有任何方法可以使用ues覆盖方法?

groogy source

import groovy.transform.CompileStatic;
interface HelloWorld {
    public void greet();
}

class HelloWorldAnonymousClassesParents {
    public void hi() {
        println "hi"
    }
}

@CompileStatic
public class HelloWorldAnonymousClasses extends HelloWorldAnonymousClassesParents {
    public void hi() {
        System.out.println("hihi ");
    }
    public void sayHello() {
        HelloWorld spanishGreeting = new HelloWorld() {
            public void greet() {
                hi() //<- here [Static type checking] - Reference to method is ambiguous error
                System.out.println("spanishGreeting");
            }
        };
        spanishGreeting.greet();
        hi()
    }

}
def myApp = new HelloWorldAnonymousClasses();
myApp.sayHello();

java中的相同源代码运行良好

java源码

package org.octopus;


class HelloWorldAnonymousClassesParents {
    public void hi() {
        System.out.println("hi ");
    }
}

interface HelloWorld {
    public void greet();
}

public class Test extends HelloWorldAnonymousClassesParents{

    public void hi() {
        System.out.println("hihi ");
    }

    public void sayHello() {
        HelloWorld spanishGreeting = new HelloWorld() {
            public void greet() {
                hi(); 
                System.out.println("spanishGreeting");
            }
        };
        spanishGreeting.greet();
        hi();
    }

    public static void main(String... args) {
        Test myApp = new Test();
        myApp.sayHello();
    }            
}

如何使用@CompileStatic注释避免该错误?

1 个答案:

答案 0 :(得分:0)

你可以把它写成一个闭包。这意味着as HelloWorld,并且因为接口只有一种方法groovy可以扣除这个。

            HelloWorld spanishGreeting = {
                    hi() 
                    System.out.println("spanishGreeting");
            }

上面的代码是groovy 2.3;对于早期的groovy 2版本,它需要一个明确的演员,如

def spanishGreeting = {/*...*/} as HelloWorld