Java动态代理实现方法

 

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

public class LogHandler implements InvocationHandler {
    private Object delegate;

    public Object bind(Object delegate) {
        this.delegate = delegate;
        return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                delegate.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result = null;
        try {
            System.out.println("方法开始:" + method);
            result = method.invoke(delegate, args);
            System.out.println("方法结束:" + method);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

 

public interface Animal {
    public void hello();
}

 

public class Monkey implements Animal {

    @Override
    public void hello() {
        // TODO Auto-generated method stub
        System.out.println("hello");
    }
}

 

public class Main {
    public static void main(String[] args) {
        LogHandler logHandler = new LogHandler();
        Animal animal = (Animal) logHandler.bind(new Monkey());
        animal.hello();
    }
}


运行结果:

 

 

 

 

 

 

 

 

 

 

 

posted @ 2014-03-20 11:22  ImWiki  阅读(927)  评论(0编辑  收藏  举报