java 动态代理

来源:互联网 发布:linux rm -f 编辑:程序博客网 时间:2024/06/03 19:28
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class FirstInvocationHandler implements InvocationHandler {    private Object target;    public FirstInvocationHandler(Object target) {        super();        this.target = target;    }    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("------------------hello------------------");        Object result = method.invoke(target, args);        System.out.println("-------------------world------------------");        return result;    }    public Object getProxy() {        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),                target.getClass().getInterfaces(), this);    }}


public interface HelloService {    void helloWorld();    }

public class HelloServiceImpl implements HelloService {public void helloWorld() {System.out.println("--------------------and ---------------");}}

public class ProxyTest {public static void main(String[] args) {HelloService userService = new HelloServiceImpl();        FirstInvocationHandler invocationHandler = new FirstInvocationHandler(userService);        HelloService proxy = (HelloService) invocationHandler.getProxy();        proxy.helloWorld();}}




原创粉丝点击