可以在运行时修改类,这样可以用声明的方式来编程(对别的代码实现无侵入式编程)。
如:
就是可以在xml文件或者什么地方声明下,即可实现对什么包或者以service结尾的的类的所有方法前后添加其他的操作。
我这就那开发者来举例吧
一个开发者的接口
/**
* @since cl @ 2019-06-19 10:26
* 开发者
*/
public interface Developer {
void code();
void debug();
}
实现一个java开发者的类
/**
* @since cl @ 2019-06-19 10:27
* Java开发者
*/
public class JavaDeveloper implements Developer{
private String name;
public JavaDeveloper(String name) {
this.name = name;
}
public void code() {
System.out.println(name+" doing code...");
}
public void debug() {
System.out.println(name+" doing debug...");
}
}
/**
* @since cl @ 2019-06-19 10:30
*/
public class JavaDeveloperHandler implements InvocationHandler {
Object object;
public JavaDeveloperHandler(Object object) {
this.object = object;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("听音乐....");
method.invoke(object,args);
System.out.println("打游戏....");
return null;
}
}
/**
* @since cl @ 2019-06-19 14:31
*/
public class DynamicProxyMain {
public static void main(String[] args) {
JavaDeveloper tomDeveloper = new JavaDeveloper("Tom");
JavaDeveloperHandler handler = new JavaDeveloperHandler(tomDeveloper);
Developer tomDeveloperProxy = (Developer)Proxy.newProxyInstance(tomDeveloper.getClass().getClassLoader(),
tomDeveloper.getClass().getInterfaces(),handler);
tomDeveloperProxy.debug();
tomDeveloperProxy.code();
}
}
《码农翻身》-Java帝国之动态代理
https://www.jianshu.com/p/95970b089360
https://www.cnblogs.com/maybo/p/5193843.html
原文:https://www.cnblogs.com/wsygdb/p/11057817.html