静态代理动态代理以及aop

静态代理和动态代理

//静态代理
interface SubClass{
	void action();
}
class SubClasss implements SubClass{
	public void action(){
		System.out.println("执行action");
	}
}
class Proxy1 implements SubClass{
	SubClasss s;
	public Proxy1(SubClasss s){
		this.s=s;
	}
	@Override
	public void action() {
		System.out.println("代理类执行");
		s.action();
	}
	
}
public class ProxyTest {
	public static void main(String[] args) {
		SubClass s = new Proxy1(new SubClasss());
		s.action();
		//动态代理
		Protest p = new Protest();
		Object o =p.blind(s);
		SubClass ss = (SubClass) o;
		ss.action();
		Childclass c = new Childclass();
		ParentClass pa =(ParentClass) p.blind(c);
		pa.action();
	}
}
//动态代理
interface ParentClass{
	void action();
}
class Childclass implements ParentClass{
	@Override
	public void action() {
		System.out.println("执行childclass的action方法");
	}
}
class Protest implements InvocationHandler{
	Object obj;
	public Object blind(Object obj){
		this.obj=obj;
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), 
				obj.getClass().getInterfaces(), this);
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("invoke方法");
		Object returnVal = method.invoke(obj, args);
		return returnVal;
	}
	
}
aop

interface Parent{
	void fly();
	void action();
}
class Child implements Parent{

	@Override
	public void fly() {
		System.out.println("i believe i can fly");
	}

	@Override
	public void action() {
		System.out.println("执行action");
	}
	
}
class ChildUtil{
	void method1(){
		System.out.println("=======方法一=======");
	}
	void method2(){
		System.out.println("=======方法二=======");
	}
}
class MyInvocation implements InvocationHandler{
	Object obj;
	void setObj(Object obj){
		this.obj=obj;
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		ChildUtil child = new ChildUtil();
		child.method1();
		Object o = method.invoke(obj, args);
		child.method2();
		return o;
	}
	
}
class Protest2{
	public static Object getProxyInstance(Object obj){
		MyInvocation m = new MyInvocation();
		m.setObj(obj);
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), 
				obj.getClass().getInterfaces(), m);
				
	}
}
public class AopTest {
	public static void main(String[] args) {
		Child c = new Child();
		Object obj = Protest2.getProxyInstance(c);
		Parent p = (Parent) obj;
		p.fly();
		p.action();
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值