public interface IHelloWorld {
void sayHello();
void sayBye();
void saySomething(String msg);
}
实例类如下:
public class HelloWorld implements IHelloWorld {
@Override
public void sayHello() {
System.out.println("Hello World");
}
@Override
public void sayBye() {
System.out.println("Bye");
}
@Override
public void saySomething(String msg) {
System.out.println("I want to say :I love you");
}
}
handler的实现类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ReflectProxy implements InvocationHandler {
private Object proxyObject;
public ReflectProxy(Object proxyObject) {
this.proxyObject = proxyObject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
doBeforeCalling(method);
method.invoke(proxyObject, args);
doAfterCalling(method);
return null;
}
private void doBeforeCalling(Method method) {
System.out.println("before calling [" + method.getName() + "]");
}
private void doAfterCalling(Method method) {
System.out.println("after calling [" + method.getName() + "]");
}
}
测试类如下:
import java.lang.reflect.Proxy;
public class ReflectProxyText {
/**
* @param args
*/
public static void main(String[] args) {
HelloWorld helloworld = new HelloWorld();
ReflectProxy handler = new ReflectProxy(helloworld);
IHelloWorld helloword = (IHelloWorld)Proxy.newProxyInstance(helloworld.getClass().getClassLoader(), helloworld.getClass().getInterfaces(), handler);
helloword.sayHello();
}
}
Spring中的通知功能也许就是使用动态代码实现的。