How to add static methods using groovy mixin

I want to use the mixin function for groovy to import methods as "class (static) methods" instead of instance methods. When I use mixin, although I have a static method in my mixin class, it is converted to an instance method in the target class. I want the imported method to be a class (static) method. Is there a good way to do this?

+4
source share
3 answers

I do not know how to add static methods to a class using mixins, but you can add static methods to a class through the metaClass.static property. Here's an example that adds a static fqn() method that prints the full class name

 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 can 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 } } 
+3
source

I + 1'd I do not answer above.

Here is what I did to get around the static mixin issue with closure, I wanted @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"} 
+1
source

I hope this will be possible in the future, which means that when this error is fixed: http://jira.codehaus.org/browse/GROOVY-4370 (Mix the class with static methods do not work properly)

0
source

Source: https://habr.com/ru/post/1304733/


All Articles