Groovy’s MetaClass

I’m not a big fan of dynamic languages, but I recently came across a situation where Groovy’s MetaClass came in extremely handy. The situation was this:

I am maintaining a Grails application that interfaces with a Java based codebase. One of the methods in this Java codebase returns a list of Data Transfer Objects (DTOs). This list is ultimately passed on to the view layer for rendering. I really wanted to add a new field to the DTO in order to avoid doing what I considered “business logic” in the view. I came up with several options:

  1. Modify the DTO.
  2. As I have control over the Java codebase, this was an option. However, the field I wanted to add really isn’t relevant in that codebase, so this really wasn’t an attractive option.

  3. Extend the DTO.
  4. Use simple object inheritance to create a new class that inherits all the public members of its parent, as well as adding the new member. This works if you don’t mind the coupling and the parent class is not finalized, and this DTO’s class is not.

  5. Wrap the DTO.
  6. This is basically the ‘decorator pattern’, and is generally favored over inheritance.

  7. Create a new DTO.
  8. Forget inheritance or composition — just create an entirely new Object that contains all the same members, as well as the new field.

  9. Groovy’s MetaClass!
  10. The idea here is we “dynamically” extend the DTO. It’s as if the class were “extended” solely for this specific use, but not in general.

The MetaClass solution was really easy to implement. After fetching the list of DTOs, we just iterate over the list to add our new field into the MetaClass:

def dtos = myBean.getDTOs()
dtos.each {
   it.metaClass.newField = < some logic here >

That’s it! The “newField” member now can be accessed by the invoking method in the regular way.

+1 for Groovy.

This entry was posted in Software Development. Bookmark the permalink.