zoukankan      html  css  js  c++  java
  • java动态代理Dynamic Proxy

    1.被代理对象的接口:

    package test.dynamicproxy;
    
    public interface TargetInterface {
    	public void SayHello();
    	public int sum(int a ,int b);
    }
    
    

    2.被代理的对象:

    package test.dynamicproxy;
    
    public class Target implements TargetInterface {
    
    	public void SayHello(){
    		System.out.println("Hello");
    	}
    	public int sum(int a, int b) {
    		return a+b;
    	}
    }
    
    

    3.InvocationHandler包装:

    package test.dynamicproxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class TargetInvocationHandler implements InvocationHandler {
    
    	private Object object;
    	public TargetInvocationHandler(Object obj){
    		this.object=obj;
    	}
    	
    	public Object invoke(Object proxy, Method method, Object[] args2)
    	throws Throwable
    	{
    		doBefore();
    		Object result = method.invoke(object, args2);
    		doAfter();
    		return result;
    	}
    
    	public void doBefore(){
    		System.out.println("do before");
    	}
    
    	public void doAfter(){
    		System.out.println("do after");
    	}
    }
    
    

    4.测试类:

    package test.dynamicproxy;
    
    import java.lang.reflect.Proxy;
    
    public class TestDynamicProxy {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		Target t=new Target();
    		TargetInvocationHandler handler=new TargetInvocationHandler(t);
    		
    		TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
    				t.getClass().getClassLoader(),
    				t.getClass().getInterfaces(),
    				handler);
    				
    		proxy.SayHello();
    
    		int b=proxy.sum(10, 20);
    		System.out.println(b);
    	}
    
    }
    
    

  • 相关阅读:
    抄来的
    getWindowHandle();
    tcp协议
    同学少年多不贱
    蓝桥 算法训练 最短路
    洛谷P1460 健康的荷斯坦奶牛 Healthy Holsteins
    蓝桥 算法提高 学霸的迷宫
    初等数论 ————拓展欧几里得算法
    CF1037D Valid BFS?
    1053 Path of Equal Weight
  • 原文地址:https://www.cnblogs.com/wucg/p/1890377.html
Copyright © 2011-2022 走看看