设计模式--动态代理

package designpattern.dynamicagent;

public interface MyInterface {

    public String helloWorld();
}
package designpattern.dynamicagent;

public class MyInterfaceImpl implements MyInterface{

    public String helloWorld(){
        return "hello world";
    }
}
package designpattern.dynamicagent;


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

public class MyInvocationHandler implements InvocationHandler {

    private Object object;

    public MyInvocationHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        Object result=method.invoke(object,args);
        System.out.println("after");
        return result;
    }
}
package designpattern.dynamicagent;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.lang.reflect.Proxy;

@ComponentScan
public class Test {

    public static void main(String[] args) throws Exception {
        System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        MyInterface myInterface=new MyInterfaceImpl();
        System.out.println(myInterface.helloWorld());
        MyInterface proxyInstance=(MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(),new Class[]{MyInterface.class},new MyInvocationHandler(myInterface));
        System.out.println(proxyInstance.helloWorld());
    }
}

设计模式--动态代理_第1张图片

 

你可能感兴趣的:(设计模式)