6 May 2011

dynamically add methods with parameters to a class in groovy

Solution based on Groovy 1.8.0

Groovy dynamic edition of Java.... scary thing, but can do crazy things.

If you are mess maker and you depend on your mother IDE who clean mess after you (using quickfix and other helpful stuff) , then Groovy you are orphan. Your mess, you problem,IDE don't care.

Back to crazyness of Groovy.One of them is adding methods dynamically to class.You can find some examples on net with one parameter,but some people would love to know how to add 2 and more parameters.

Let's say you have Date class which has lots of funky method,but you wish to add another one to check is specific date is in range of time (lets say between 01-06-2011 and 01-11-2011 ).
How to add dynamically add methods with parameters to a class in groovy ?

NAMEofClass.metaClass.nameOfMethord = { Type parameter1, Type parameter2, Type parameter3 ->
method that will do marvellous and cool stuff
}

Date.metaClass.between = { String dateStart,String dateEnd,Date date ->
 def dateFormat = 'dd-MM-yyyy'
Date start = Date.parse(dateFormat,dateStart)
Date end = Date.parse(dateFormat,dateEnd)

if( (start > delegate).equals(-1) && (end > delegate).equals(1)){
return true
}else {
return false
  }

}


and then in your class you just need ....

boolean isInRange(Date date){
  return date.between(" 01-06-2011 ","  01-11-2011  ",date))
}

What to do when i must add dynamically added method of one class in other ????

Put "dynamically added method of Source Class( Date)" intro costructor of class where you will use Source class method.