静态代理动态代理以及aop

来源:互联网 发布:中欧基金 知乎 编辑:程序博客网 时间:2024/06/02 05:01

静态代理和动态代理

//静态代理interface SubClass{void action();}class SubClasss implements SubClass{public void action(){System.out.println("执行action");}}class Proxy1 implements SubClass{SubClasss s;public Proxy1(SubClasss s){this.s=s;}@Overridepublic void action() {System.out.println("代理类执行");s.action();}}public class ProxyTest {public static void main(String[] args) {SubClass s = new Proxy1(new SubClasss());s.action();//动态代理Protest p = new Protest();Object o =p.blind(s);SubClass ss = (SubClass) o;ss.action();Childclass c = new Childclass();ParentClass pa =(ParentClass) p.blind(c);pa.action();}}//动态代理interface ParentClass{void action();}class Childclass implements ParentClass{@Overridepublic void action() {System.out.println("执行childclass的action方法");}}class Protest implements InvocationHandler{Object obj;public Object blind(Object obj){this.obj=obj;return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("invoke方法");Object returnVal = method.invoke(obj, args);return returnVal;}}
aop

interface Parent{void fly();void action();}class Child implements Parent{@Overridepublic void fly() {System.out.println("i believe i can fly");}@Overridepublic void action() {System.out.println("执行action");}}class ChildUtil{void method1(){System.out.println("=======方法一=======");}void method2(){System.out.println("=======方法二=======");}}class MyInvocation implements InvocationHandler{Object obj;void setObj(Object obj){this.obj=obj;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {ChildUtil child = new ChildUtil();child.method1();Object o = method.invoke(obj, args);child.method2();return o;}}class Protest2{public static Object getProxyInstance(Object obj){MyInvocation m = new MyInvocation();m.setObj(obj);return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), m);}}public class AopTest {public static void main(String[] args) {Child c = new Child();Object obj = Protest2.getProxyInstance(c);Parent p = (Parent) obj;p.fly();p.action();}}



0 0
原创粉丝点击