Wednesday, June 07, 2006

AOP and Java Annotations

In this post I wish to show how the combination of annotations and AOP can be used to perform a "parameter cannot be null" validation in a class' method.

Suppose we have the following method that is executed only if the parameter value is not null:


public void serviceNotAllowedNullParameter(Object param){
if( param != null ){

System.out.println(param.toString());

//do something...

}

}


One possibility is to include the same code if (copy paste the same code pattern) in all methods that need this behavior. Another one ( much more elegant ) is design a solution based on AOP and Annotations. Let’s start by defining the NotNullParameter annotation as following:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)

public @interface NotNullParameter {

}


Now, we proceed to decorate the method with the @NotNullParameter:

@NotNullParameter
public void serviceNotAllowedNullParameter(Object param){

if( param != null ){

System.out.println(param.toString());

//do something...
}
}


Though, so far we don’t do any magic. We need to find the (fashion) way to process all annotations that were defined in our code in order to add the necessary logic to perform the check validation. So… a good idea would be to use an Aspect!


void around(Object param):
execution(@NotNullParameter void ar.adalon..*.*(Object+) ) &&

args(param){

if( param == null ){

return;

}

proceed(param);

}


The preceding code is read as simple as “Intercept all the execution of any method of any package or sub package of ar.adalon that accept one parameter (of type or subtype of object… hence is any instance) and is decorated with the @NotNullParameter annotation”. The around advise allows to continue (procced) or terminate (return;) with the intercepted method’s execution. Now, we can simplify our service to:


@NotNullParameter
public void serviceNotAllowedNullParameter(Object param){
System.out.println(param.toString());
//do something...
}

By this way, I intended to show you how AOP crosscutting allow to break up the business logic and additional validations .


I leave some helpful links concerning annotations:

http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html
http://www.developer.com/java/other/article.php/10936_3556176_1
http://java.sun.com/developer/technicalArticles/releases/j2se15/
http://www-128.ibm.com/developerworks/java/library/j-annotate1/
http://www-128.ibm.com/developerworks/library/j-annotate2.html
http://www.devsource.com/article2/0,1895,1949936,00.asp


Labels:


This page is powered by Blogger. Isn't yours?