Java 动态代理

       在Java程序设计中,有两个特性非常重要,一个是IOC,另一个就是AOP。IOC应用非常广泛,这里就不说了,AOP应用得比较少,原理剖析得也比较少。今天写了一个AOP的例子来帮助分析AOP的原理。AOP是通过动态代理来实现的,任何一个动态代理的类必须实现InvocationHandler这个接口,这个接口的唯一方法-Invoke即函数调用的入口。通常我们需要使用AOP的类需要实现一个接口,方便注入到动态代理类中,这样也方便做扩展(其实还是使用了IOC的一些东西),这样的方式能够确保AOP的灵活性。

1.Process接口      

public interface Process {
	
	public void Start();
	
	public void Action(String message);
}
2.ProcessImple类实现 Process接口

public class ProcessImple implements Process {

	@Override
	public void Start() {
		// TODO Auto-generated method stub
		System.out.println("process start.");
	}

	@Override
	public void Action(String message) {
		// TODO Auto-generated method stub
		System.out.println("process: " + message);
	}
<pre name="code" class="java">import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;


public class ProxyClient {
	public static void main(String[] args){
		
		Process processImpl = new ProcessImple();
		InvocationHandler handler= new DynamicProxy(processImpl);	
		
		Process process = (Process)Proxy.newProxyInstance(handler.getClass().getClassLoader(), processImpl
                .getClass().getInterfaces(), handler);
        
        //System.out.println(subject.getClass().getName());
		process.Start();
		process.Action("GET ALL MONEY.");
		
	}
}

}

 3.DynamicProxy(动态代理类) 

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

public class DynamicProxy implements InvocationHandler {

	private Object process;
	
	public DynamicProxy(Object process){
		this.process = process;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("before process.");
		//System.out.println("Method:" + method);
		method.invoke(process, args);
		System.out.println("after process");
		return null;
	}
}
4.ProxyClient(调用类)
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;


public class ProxyClient {
	public static void main(String[] args){
		
		Process processImpl = new ProcessImple();
		InvocationHandler handler= new DynamicProxy(processImpl);	
		
		Process process = (Process)Proxy.newProxyInstance(handler.getClass().getClassLoader(), processImpl
                .getClass().getInterfaces(), handler);
        
        //System.out.println(subject.getClass().getName());
		process.Start();
		process.Action("GET ALL MONEY.");
		
	}
}

运行下,看输出结果:

before process.
process start.
after process
before process.
process: GET ALL MONEY.
after process
这时候我们可以看到动态代理里面的方法都被调用了,AOP非常适合做日志功能,类似ASP.NET MVC里面的filter功能。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值