hi, I want to use the mixin feature of 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?
+1
A:
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
}
}
Don
2010-03-22 14:45:39