Groovy metaprogramming with Java
Say I have a large collection of Java static methods in a class of only static methods. All of them apply to some type of collection class. How can I scan this class, and using Groovy add each of them to the respective metaclasses?
So a sample might look something like this:
public class CollectionUtilities {
public static <T> T duplicates(Collection<T> coll) {
return // some code to isolate the duplicates
}
}
I'd want that to end up so I could call [1, 2, 2].duplicates()
=> [2]
Collection.metaClass.duplicates = { -> // replace coll usages with delegate }
Has anyone done anything like this?
Any idea of a g开发者_运维知识库ood way to go about it?
You're on the right track with categories. A category can be employed locally as you demonstrated with your answer, or globally via mixin
.
To add every method of your CollectionUtilities class to Collections at runtime, you can simply do the following:
Collection.mixin CollectionUtilities
I've found I can use the 'use' keyword to magically pull in a class like so:
use(src.CollectionUtilities) {
[1, 2, 3, 3].duplicates()
}
=> [3]
This is more of a brute force technique, and the code using the methods has to be contained within the clojure, I wonder still if there is a more precise way to do this......
精彩评论