1. 程式人生 > >JDK動態代理(JDK dynamic proxy)

JDK動態代理(JDK dynamic proxy)

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK動態代理。
 * @author Bright Lee
 */
public class JdkDynamicProxyTest {
	
	public static void main(String[] args) {
		Interface target = new Class();
		JdkDynamicProxyHandler handler = new JdkDynamicProxyHandler(target);
		
		Interface proxy = (Interface) Proxy.newProxyInstance(
				target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(), 
				handler);
		
		String result = proxy.getName();
		System.out.println(result);
	}

}

/**
 * 定義一個介面,由動態代理實現該介面,並進行增強。
 */
interface Interface {
	
	public String getName();
	
}

/**
 * 介面的實現類。
 */
class Class implements Interface {

	public String getName() {
		return "MyName";
	}
	
}

class JdkDynamicProxyHandler implements InvocationHandler {
	
	private Object target;
	
	public JdkDynamicProxyHandler(Object target) {
		this.target = target;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if (method.getName().equals("getName")) {
			String name = (String) method.invoke(target, args);
			name = "My name is: " + name;
			return name;
		} else {
			return null;
		}
	}
	
}

執行結果:
My name is: MyName