Groovy expando metaclass

I developed a class that has some methods that complement Integer, basically this allows me to do this:

def total = 100.dollars + 50.euros

Now I need to extend Integer.metaClass by doing something like this:

Integer.metaClass.getDollars = {->
    Money.Dollar(delegate)
}

I tried to put this at the bottom of the file before declaring the Money class, but the compiler says that the Named Money class already exists, I know why this happens (because groovy creates a class called file with empty static void main to run this code).

I also tried using a static block inside the class as follows:

static {
    Integer.metaClass.getDollars = {->
        Money.Dollar(delegate)
    }
}

This does not work.

A third solution would be to change the file name (e.g. MoneyClass.groovy) and keep the class name (Money class), but that seems a bit odd.

Is there anything else I can do? Thanks.

+3
1

, , bean TypeEnhancer.groovy:

public class TypeEnhancer {
  public void start() {
    Integer.metaClass.getDollars() = {-> Money.Dollar(delegate) }
  }

  public void stop() {
    Integer.metaClass = null
  }
}

, start(): new TypeEnhancer().start();. , new TypeEnhancer().stop();. bean Spring bean.

+2

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


All Articles