反射とダイナミックエージェントは、コンテキストカットのAOP効果を実現します。
5967 ワード
Javaの反射フレームワークは、動的エージェント機構を提供し、動作中にターゲットクラスに対してプロキシを生成することができ、繰り返し開発を回避し、コンテキストカットの機能を実現する。
コードは最高のコミュニケーション言語です。
Subjectインターフェース
RealSubject実現インターフェース
SubjectHandlerはコンテキスト切り込みを実現し、非明示的な動的エージェント機能を実現する。
以下はどうやって呼び出しますか?
コードは最高のコミュニケーション言語です。
Subjectインターフェース
RealSubject実現インターフェース
SubjectHandlerはコンテキスト切り込みを実現し、非明示的な動的エージェント機能を実現する。
interface Subject {
public String request(int[] array);
public void anotherRequest();
}
public class RealSubject implements Subject {
@Override
public String request(int[] array) {
System.out.println("real do something");
for(int at:array) {
System.out.print(at+" ");
}
System.out.println();
return "";
}
@Override
public void anotherRequest() {
System.out.println("anotherRequest");
}
public void ownMethod() {
System.out.println("ownMethod");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class SubjectHandler implements InvocationHandler{
private Subject subject;
public SubjectHandler(Subject _subject) {
subject = _subject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(" ... ");
Object obj = method.invoke(subject, args);
System.out.println(" ... ");
return obj;
}
}
以下はどうやって呼び出しますか?
public static void main(String[] args) {
Subject subject = new RealSubject();
InvocationHandler handler = new SubjectHandler(subject);
ClassLoader cl = subject.getClass().getClassLoader();
/*
* Returns an instance of a proxy class for the specified interfaces
* that dispatches method invocations to the specified invocation handler.
* Subject
*/
Subject proxy = (Subject) Proxy.newProxyInstance(cl, subject.getClass().getInterfaces(), handler);
// ,
int[] array = {1,2,3};
String a =proxy.request(array);
System.out.println(a);
//
proxy.anotherRequest();
/**
* !
* , Subject,
* handler , invoke , , AOP
*/
}
以下のように入力します ...
real do something
1 2 3
...
...
anotherRequest
...