jdk动态代理技术demo(干货)

时间:2022-08-20 15:19:50

学习完jdk动态代理以后,写的demo。为了方便以后查阅,特将代码贴
到博客上,以后有时间再详细讲解
通知接口
package com.me.aop;

public interface IAdvice {
void befor();
void after();
}


通知实现类,完成日志打印

package com.me.aop;

public class LogAdvice implements IAdvice {

@Override
public void befor() {
System.out.println("方法开始");
}

@Override
public void after() {
System.out.println("方法结束");
}

}

代理实现方式有多种,例如jdk、cglib...

package com.me.aop;

public interface IProxyProvider {
Object getProxyObj();
}

jdk实现
package com.me.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyImpl implements IProxyProvider {

private IAdvice advice;
private Object target;

public JDKProxyImpl() {
}
public JDKProxyImpl(IAdvice IAdvice, Object target) {
this.advice = IAdvice;
this.target = target;
}

public IAdvice getAdvice() {
return advice;
}
public void setAdvice(IAdvice advice) {
this.advice = advice;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
@Override
public Object getProxyObj() {
Object obj = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(advice != null){
advice.befor();
}
Object result = method.invoke(target, args);
if(advice != null){
advice.after();
}
return result;
}
});
return obj;
}

}

由于jdk动态代理要求代理的对象必须实现最少一个接口
package com.me.aop;

public interface Caculator {
int substrct(int a,int b);
}

package com.me.aop;

public class CaculaterImpl implements Caculator {

@Override
public int substrct(int a, int b) {
System.out.println("方法执行中.....");
return a-b;
}

}

客户端
package com.me.aop;


public class Client {
public static void main(String[] args) {
//测试jdk动态代理
IAdvice logAdvice = new LogAdvice();
Caculator caculator = new CaculaterImpl();
IProxyProvider proxyProvider = new JDKProxyImpl(logAdvice,caculator);
Caculator caculatorProxy = (Caculator) proxyProvider.getProxyObj();
System.out.println(caculatorProxy.substrct(3, 1));
}


}

亲测可用!