1、接口
public interface Foo {
void modify();
void ff(int x);
}2、被代理类
public class FooImpl implements Foo {
@Override
public void modify() {
System.out.println("*******modify()方法被调用");
}
@Override
public void ff(int x) {
System.out.println("ff()方法被调用啦啊啊啊啊啊啊啊");
}
}3、动态代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object o=null;
public MyInvocationHandler(Object o){
this.o=o;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(method.getName()+"被调用,参数:"+args[0].toString());
Object ret = method.invoke(this.o, args);
System.out.println(method.getName()+"调用结束");
return ret;
}
}4、测试程序及结果
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
public class ProxyClass {
public static void main(String arags[]) throws IllegalArgumentException,
SecurityException, InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
InvocationHandler handler = new MyInvocationHandler(new FooImpl());
Class proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(),
new Class[] { Foo.class });
Foo f = (Foo) proxyClass.getConstructor(
new Class[] { InvocationHandler.class }).newInstance(
new Object[] { handler });
//f.modify();
f.ff(2211);
}
}原文:http://5070780.blog.51cto.com/5060780/1360500