Spring AOP动态代理

package com.test.dynamicproxy;

public interface Subject
{
	public void request();
}
package com.test.dynamicproxy;

public class RealSubject implements Subject
{
	public void request()
	{
		System.out.println("From real subject!");
	}
}
package com.test.dynamicproxy;

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

public class DynamicSubject implements InvocationHandler
{
	private Object sub;

	public DynamicSubject(Object obj)
	{
		this.sub = obj;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable
	{
		System.out.println("before calling: " + method);

		method.invoke(sub, args);

		System.out.println(args == null);

		System.out.println("after calling: " + method);

		return null;
	}

}
package com.test.dynamicproxy;

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

public class Client
{
	public static void main(String[] args)
	{
		RealSubject realSubject = new RealSubject();

		InvocationHandler handler = new DynamicSubject(realSubject);

		Class<?> classType = handler.getClass();

		Subject subject = (Subject) Proxy.newProxyInstance(classType
				.getClassLoader(), realSubject.getClass().getInterfaces(),
				handler);

		subject.request();

		System.out.println(subject.getClass());

	}

}

相关推荐