zoukankan      html  css  js  c++  java
  • 18.5.2动态代理和AOP

    ----此处是JDK动态代理----
    package d18_5_2; public interface IDog { void info(); void run(); }
    package d18_5_2;
    
    public class GunDog implements IDog {
    
    	@Override
    	public void info() {
    		System.out.println("DunDog 我是一只猎狗!");
    	}
    
    	@Override
    	public void run() {
    		System.out.println("GunDog 我奔跑迅速!");
    	}
    
    }
    

      

    package d18_5_2;
    
    public class DogUtil {
    
    	public void beforeMethod() {
    		System.out.println("DogUtil beforeMethod");
    	}
    
    	public void afterMethod() {
    		System.out.println("DogUtil afterMethod");
    	}
    }
    

      

    package d18_5_2;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class MyInvocationHandler implements InvocationHandler {
    	// 需要被代理的对象
    	private Object target;
    
    	public void setTarget(Object target) {
    		this.target = target;
    	}
    
    	@Override
    	public Object invoke(Object proxy, Method method, Object[] args)
    			throws Throwable {
    		DogUtil du = new DogUtil();
    		du.beforeMethod();
    		Object result = method.invoke(target, args);
    		du.afterMethod();
    		return result;
    	}
    
    }
    

      

    package d18_5_2;
    
    import java.lang.reflect.Proxy;
    
    public class MyProxyFactory {
    	// 为指定target生成动态代理对象
    	public static Object getProxy(Object target) {
    		// 创建一个MyInvocationHandler对象
    		MyInvocationHandler handler = new MyInvocationHandler();
    		// 为MyInvocationhandler指定target
    		handler.setTarget(target);
    		return Proxy.newProxyInstance(target.getClass().getClassLoader(),
    				target.getClass().getInterfaces(), handler);
    	}
    }
    

      

    package d18_5_2;
    
    public class TestDog {
    
    	public static void main(String[] args) {
    		IDog target=new GunDog();
    		IDog dog = (IDog)MyProxyFactory.getProxy(target);
    		dog.info();
    		dog.run();
    	}
    
    }
    

      

  • 相关阅读:
    Count and Say leetcode
    Find Minimum in Rotated Sorted Array II leetcode
    Find Minimum in Rotated Sorted Array leetcode
    Search in Rotated Sorted Array II leetcode
    search in rotated sorted array leetcode
    Substring with Concatenation of All Words
    Subsets 子集系列问题 leetcode
    Sudoku Solver Backtracking
    Valid Sudoku leetcode
    《如何求解问题》-现代启发式方法
  • 原文地址:https://www.cnblogs.com/1020182600HENG/p/7360867.html
Copyright © 2011-2022 走看看