简体   繁体   中英

Is threre any way to ues override method in anonymous class on Groovy @CompileStatic annotation

Is threre any way to ues override method in anonymous class on Groovy @CompileStatic annotation?

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();

Same source in java run well

java source

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();
    }            
}

How can I avoid that error with @CompileStatic annotation?

You can write it as a closure. This implies an as HelloWorld and as the interface only has one method groovy can deduct this.

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

above code is groovy 2.3; with earlier groovy 2 versions it needs an explicit cast like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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