Java代理(Aop实现的原理)

经过大牛同事的一句指点立马明确的代理实现方式,Spring Aop应该也是这么去做的。直接上代码

实如今Car的run方法之前调用star方法,在run方法之后调用stop方法。

Car类

package com.lubby.test;

public class Car {
	public void run() {
		System.out.println("I am running....");
	}
}


Car的run方法之前和之后调用的方法

package com.lubby.test;

public class Something {

	public void star() {
		System.out.println("check the car...");
	}

	public void stop() {
		System.out.println("stop the car");
	}
}

利用另外的一个类继承Car。事实上就是传说中的代理类。

复写run方法,在调用Car 的run方法之前调用star方法。run方法之后调用stop方法。

package com.lubby.test;

public class ProxyClass extends Car {

	@Override
	public void run() {
		Something something = new Something();
		something.star();
		super.run();
		something.stop();
	}

	public static void main(String[] args) {
		try {
			ProxyClass proxyClass = (ProxyClass) Class.forName("com.lubby.test.ProxyClass").newInstance();
			proxyClass.run();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

打印结果

check the car...
I am running....
stop the car


猜你喜欢

转载自www.cnblogs.com/ldxsuanfa/p/10628702.html