public interface HelloWorld {
void sayHello(String name);
}
public class HelloWorldImpl implements HelloWorld {
@Override
public void sayHello(String name) {
System.out.println("hello " + name);
}
}
下面这个类很重要,实现了InvocationHandler接口。
public class CustomInvocationHandler implements InvocationHandler {
private Object target;
public CustomInvocationHandler(Object object) {
this.target = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object retVal = method.invoke(target, args);
System.out.println("after");
return retVal;
}
}
public class ProxyTest {
public static void main(String[] args) {
CustomInvocationHandler handler = new CustomInvocationHandler(new HelloWorldImpl());
HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[]{HelloWorld.class}, handler);
proxy.sayHello("dezhonger");
}
}
输出:
before
hello dezhonger
after