groovyinterfacestaticstatic-methods

Is there any way to make Groovy 4.0.x compile interfaces with static methods?


I want to make an interface with some static methods for decorating instances or adapting them to other interfaces. However, Groovy 4.0.x gives an error when trying to do this, probably because it's meant to be compatible with JDK 8, which didn't allow this yet. However, I am not interested in my program being compatible with JDK versions before 11, which I think is when static interface methods became available. Is there some compiler setting that allows me to have static methods on interfaces, or perhaps an AST hack?


Solution

  • If you need a true java interface with a static method - it's not supported in groovy 4.0. Seems it's going to be available in 5.0 https://issues.apache.org/jira/browse/GROOVY-11237

    It's not clear what you need to achieve but here is a way to declare static method for interface in groovy using metaprogramming:

    interface A {}
    
    A.metaClass.static.f = { x -> "hello $x!" }
    
    A.f("world")
    

    returns hello world!

    If you have a maven or gradle groovy project, then you can configure to compile java files just before groovy and implement the interface with static methods using java.