基於jdk的動態代理實現
阿新 • • 發佈:2021-02-11
目標物件介面
Target.java
public interface Target {
public void save();
}
目標物件實現
TargetImpl.java
import com.itheima.Target;
public class TargetImpl implements Target {
public void save() {
System.out.println("running.......");
}
}
通知,功能目標
Advice.java
public class Advice {
public void before(){
System.out.println("前置加強");
}
public void afterRunning(){
System.out.println("後置加強");
}
}
測試類
import com.itheima.impl.TargetImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
final TargetImpl target = new TargetImpl();
final Advice advice = new Advice();
//返回值 就是生成的動態代理物件
Target proxy = (Target) Proxy.newProxyInstance(
target. getClass().getClassLoader(), //目標物件的載入器
target.getClass().getInterfaces(), //目標物件相同的介面位元組碼物件陣列
new InvocationHandler() {
//呼叫代理物件的任何方法,實際是執行invoke();
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.before();
Object invoke = method.invoke(target, args);//執行目標物件方法
advice.afterRunning();
return invoke;
}
}
);
proxy.save();
}
}
執行結果