使用 Java 代理类

HelloWorld.java

package net.lnmcc.www;

public interface HelloWorld {
	public void sayHelloWorld();
	public void sayGoodBye();
}

HelloWorldHandler.java

package net.lnmcc.www;

import java.lang.reflect.*;

public class HelloWorldHandler implements InvocationHandler {
	private Object obj;

	public HelloWorldHandler(Object obj) {
		super();
		this.obj = obj;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;

		System.out.println("before...");
		result = method.invoke(obj, args);
		System.out.println("after...");
		return result;
	}
}

HelloWorldImpl.java

package net.lnmcc.www;

public class HelloWorldImpl implements HelloWorld {
	public void sayHelloWorld() {
		System.out.println("Hello world");
	}
	public void sayGoodBye() {
		System.out.println("GoodBye");
	}
}

ProxyTest.java

package net.lnmcc.www;

import java.lang.reflect.*;

public class ProxyTest {
	public static void main(String[] args) {
		HelloWorld helloWorld = new HelloWorldImpl();
		InvocationHandler handler = new HelloWorldHandler(helloWorld);
		HelloWorld proxy = (HelloWorld)Proxy.newProxyInstance(helloWorld.getClass().getClassLoader(), 
				helloWorld.getClass().getInterfaces(),
				handler);
		proxy.sayHelloWorld();
		proxy.sayGoodBye();
	}
}