public interface IHello {
public void say(String name);
public void play(String sth);
}
public class HelloImp implements IHello{
@Override
public void say(String name) {
System.out.println("Hello: "+name);
}
@Override
public void play(String sth) {
System.out.println("Play: "+sth);
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class LogHandler implements InvocationHandler {
private Object bindObj;
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("before....");
Object result = method.invoke(bindObj, args);
System.out.println("after....");
return result;
}
public Object bind(Object bindObj){
this.bindObj = bindObj;
return Proxy.newProxyInstance(bindObj.getClass().getClassLoader(), bindObj.getClass().getInterfaces(), this);
}
}
public class ProxyDemo {
/**
* @param args
*/
public static void main(String[] args) {
LogHandler logHandler = new LogHandler();
IHello hello = (IHello)logHandler.bind(new HelloImp());
hello.say("callan");
hello.play("football");
}
}
动态代理
最新推荐文章于 2025-03-19 08:00:00 发布