たとえば、Proxy.newProxyInstanceはハートを使用するJavaの動的プロキシ

プロキシクラスのJDK使用静的メソッドnewProxyInstance、JVMが自動的に新しいクラスを生成するために聞かせて、クラスはすべてのメソッドinerfacesのパラメータが含まれ、各メソッド呼び出しメソッドh.invoke
 
 
 
ダイナミックプロキシAOP
 
パッケージcom.atguigu.spring.aop。
 
輸入java.lang.reflect.InvocationHandler;
輸入java.lang.reflect.Methodオブジェクト;
輸入java.lang.reflect.Proxyの;
輸入java.util.Arrays。
 
//プロキシクラス
パブリッククラスArithmeticCalculatorLoggingProxy {
 
// 1.プロキシされているオブジェクトターゲットオブジェクト
プライベートArithmeticCalculator目標; //実際にArithmeticCalculatorImplオブジェクト。
 
//ターゲットオブジェクトを介してコンストラクタが渡されます
公共ArithmeticCalculatorLoggingProxy(ArithmeticCalculator対象){
this.target =ターゲット。
}
 
//プロキシオブジェクトを取得します。
公共ArithmeticCalculator getLoggingProxy(){
//プロキシオブジェクトを定義します
ArithmeticCalculatorプロキシ。
 
/ **
* Loaderの:ClassLoaderクラスローダー
*インターフェース:すべてのインターフェイスが目指す目標クラスがインターフェイスを取得することでした
* H:のInvocationHandler
* /
ClassLoader loader = target.getClass().getClassLoader();
Class[] interfaces = target.getClass().getInterfaces();
InvocationHandler h = new InvocationHandler() {
/**
* proxy:代理对象 在invoke方法中一般不会用
* method:正在调用的方法
* args:调用方法传入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName = method.getName();
//加日志
System.out.println("ATGUIGU===>The method "+methodName+" begins with "+ Arrays.asList(args));
//执行目标方法
Object result = method.invoke(target, args);
//加日志
System.out.println("ATGUIGU===>The method "+methodName+" ends with " + result );
return result;
}
};
 
proxy = (ArithmeticCalculator)Proxy.newProxyInstance(loader, interfaces, h);
 
 
使用JDk的Proxy的静态方法 newProxyInstance ,让JVM自动生成一个新的类,类中包含了inerfaces参数中的所有方法,每个方法都调用h.invoke 方法
return proxy ;
}
 
 
}
 

おすすめ

転載: www.cnblogs.com/jiangtao1218/p/11862907.html