2

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 good way to go about it?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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......

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.