Wednesday, June 1, 2011

Aspects in Java

Aspects in Java
Lets take an example of a Student class. Student class is responsible for calculating marks of a Student.


class Student{
calculateTotalMarks(){
....
....
}
}
Now, after six months, your manager tells you to add some code, which will be called before calculateTotalMarks () method will be called.

One solution is to add that code above the first line of method statement. For e.g
class Student{
calculateTotalMarks (){
// Do what manager told me to do
....
….
}
}

But, it might happen that this method is being called from some other places in your project. So, changing calculateTotalMarks() may break the code.
This is where aspects come into picture. You don’t need to modify Student class. Simply create an aspect class and define pointcuts. For example:

public aspect StudentAspect {
pointcut monitorStudent()
: execution(* Student.calculateTotalMarks (..));

before() : monitorStudent (){
getStudentDetails();
}

after():monitorStudent (){
calculateAverageMarks();
}
}

Here, I have defined a StudentAspect aspect class and before/after pointcuts. When ever calculateTotalMarks method of Student will be called, getStudentDetails will be called before that and after execution of calculateTotalMarks method, calculateAverageMarks method will be called.

-getStudentDetails method will be called
-calculateTotalMarks method will be called
-calculateAverageMarks method will be called

Syntax
pointcut monitorStudent()
: execution(* Student.calculateTotalMarks (..));

Pointcut monitorStudent() – declare pointcut with name monitorStudent

execution(* Student.calculateTotalMarks (..)) – Apply pointcuts to any method which resides in any package with Student as class name and calculateTotalMarks as method name with any number of arguments.

1 comment:

  1. Aspects in java. Nice Post . Thanks for sharing this information which is useful for all.

    php web development

    ReplyDelete