java動態代理(1)

為不為發表於2018-12-06

程式碼

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

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;



public class Main {
    public static void main(String[] args) {
    	//java動態代理   需要有介面
        RealObject real = new RealObject();
        Interface proxy = (Interface) Proxy.newProxyInstance(
                Interface.class.getClassLoader(), new Class[] {Interface.class},
                new DynamicProxyHandler(real));
        
        proxy.doSomething();
        proxy.somethingElse("gg");
        //cglib動態代理
        BookFacadeImpl1 bookFacade=new BookFacadeImpl1();
        BookFacadeCglib  cglib=new BookFacadeCglib();  
        BookFacadeImpl1 bookCglib=(BookFacadeImpl1)cglib.getInstance(bookFacade);  
        bookCglib.addBook();  
    }
}
//java動態代理
 class DynamicProxyHandler implements InvocationHandler {
    private Object proxyed;
    
    public DynamicProxyHandler(Object proxyed) {
        this.proxyed = proxyed;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("代理工作了.");
        return method.invoke(proxyed, args);
    }
}
 interface Interface {
    void doSomething();
    void somethingElse(String arg);
}
 class RealObject implements Interface {
    public void doSomething() {
        System.out.println("doSomething.");
    }
    public void somethingElse(String arg) {
        System.out.println("somethingElse " + arg);
    }
}
 //cglib動態代理
 class BookFacadeImpl1 {  
	    public void addBook() {  
	        System.out.println("新增圖書...");  
	    }  
} 
  class BookFacadeCglib implements MethodInterceptor {  
	    private Object target;//業務類物件,供代理方法中進行真正的業務方法呼叫
	  
	    //相當於JDK動態代理中的繫結
	    public Object getInstance(Object target) {  
	        this.target = target;  //給業務物件賦值
	        Enhancer enhancer = new Enhancer(); //建立加強器,用來建立動態代理類
	        enhancer.setSuperclass(this.target.getClass());  //為加強器指定要代理的業務類(即:為下面生成的代理類指定父類)
	        //設定回撥:對於代理類上所有方法的呼叫,都會呼叫CallBack,而Callback則需要實現intercept()方法進行攔
	        enhancer.setCallback(this); 
	       // 建立動態代理類物件並返回  
	       return enhancer.create(); 
	    }
	    // 實現回撥方法 
	    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 
	        System.out.println("預處理——————");
	        proxy.invokeSuper(obj, args); //呼叫業務類(父類中)的方法
	        System.out.println("呼叫後操作——————");
	        return null; 
	    }
  }

輸出

代理工作了.
doSomething.
代理工作了.
somethingElse gg
預處理——————
新增圖書...
呼叫後操作——————

相關文章