开发者

how to add static methods using groovy mixin

开发者 https://www.devze.com 2022-12-24 11:28 出处:网络
I want to use the mixin feature o开发者_运维技巧f groovy to import methods as \"class(static) methods\" instead of instance methods. When i use mixin even though i have a static method in my mixin cla

I want to use the mixin feature o开发者_运维技巧f groovy to import methods as "class(static) methods" instead of instance methods. When i use mixin even though i have a static method in my mixin class it gets converted into a instance method in the destination class.I want the imported method to be a class(static) method.Is there a good way to do it?


I don't know of any way to add static methods to a class using mixins, but you can add static methods to a class via the metaClass.static property. Here's an example that adds a static fqn() method that prints the fully-qualified name of a class

Class.metaClass.static.fqn = { delegate.name }
assert String.fqn() == "java.lang.String"

If you want to add fqn() (and other static methods) to several classes (e.g. List, File, Scanner), you could do something like

def staticMethods = [fqn: {delegate.name}, fqnUpper: {delegate.name.toUpperCase()}]    

[List, File, Scanner].each { clazz ->

    staticMethods.each{methodName, methodImpl ->
        clazz.metaClass.static[methodName] = methodImpl
    }
}


I +1'd Don's reply above.

Here's what I did to get around static mixin issue with closures I wanted to @Mixin.

Class Foo {

    static a = {}
    static b = {}
    static c = {}
}

Class Bar {}

def meths = Foo.metaClass.properties.findAll{it.type==Object}.collect{it.name}  
meths.each {Bar.metaClass.static."$it" = A."$it"}


I hope it will be possible in future, it means, when this bug will be fixed: http://jira.codehaus.org/browse/GROOVY-4370 (Mixin a class with static methods is not working properly)

0

精彩评论

暂无评论...
验证码 换一张
取 消