AspectJAdvertisementAspectJとは
AspectJとは、Javaでアスペクト指向を実現するための言語である。
アスペクトの指定は、Javaプログラムとは別の場所で行うため、既存のJavaオブジェクトをそのまま利用することができる。 よって、新たなアスペクトの追加や定義済みアスペクトの削除などを容易に行うことが出来る。 入手
Officialサイトはhttp://eclipse.org/aspectj/
EclipseでAspectJを利用するためのAJDTプラグインはhttp://www.eclipse.org/ajdt/で入手可能。 簡単なサンプル
POJO
public class Users {
public static void main(String[] args){
new Users().printNames();
}
public void printNames(){
System.out.println("my name is taro");
}
}
aspect
import java.util.Date;
aspect NowDate {
pointcut user(): call(void sample.Users.printNames());
before(): user() {
System.out.println(new Date());
}
after(): user() {
System.out.println(new Date());
}
}
結果 Mon Feb 21 0:00:00 JST 2005 my name is taro Mon Feb 21 0:00:00 JST 2005 Aspectの構成PointcutJoinpointの設定位置を定義する。文法 pointcut [Joinpoint名]([引数リスト]): [Joinpoint]; Joinpointプログラム上の任意の位置をポイントとして定義する。
Adviseどのような処理を行うか記述する
AspectAdvice,Joinpoint,Pointcutの関連付けを行うための単位。例
import java.util.Date;
aspect NowDate {
pointcut user(): call(void sample.Users.printNames());
before(): user() {
System.out.println(new Date());
}
after(): user() {
System.out.println(new Date());
}
}
動作確認サンプル
Test.java
public class Test {
public static void main(String[] args) throws Exception{
new Test().testMethod("test");
}
public void testMethod(String str) throws Exception{
System.out.println(str);
throw new Exception("exception");
}
}
Test.aj
aspect Test {
pointcut test():call(void logic.Test.testMethod(String));
before(String str) : test() && args(str){
System.out.println("before()");
System.out.println("\tstr:" + str);
System.out.println("\tthis.class:" + this.getClass());
}
after() : test(){
System.out.println("after()");
}
before() returning : test(){
System.out.println("before returning()");
}
after() returning : test(){
System.out.println("after returning()");
}
before() throwing : test(){
System.out.println("before() throwing");
}
after() throwing : test(){
System.out.println("after() throwing");
}
}
結果
before()
str:TEST
this.class:class Test
TEST
after()
before() throwing
after() throwing
java.lang.Exception: exception
at Test.testMethod(Test.java:12)
at Test.main(Test.java:5)
Exception in thread "main"
メモ
Advertisement |
ショートカット・634トップページ・このカテゴリのトップページに戻る ・634ラボ サイト検索Y!ログール |