java動態代理

java靜態代理沒什麼好說,所謂的代理 就是一種中介。假如你在java裏面有個接口的方法要拓展,可是你又不想在這個方法裏面去改原先的邏輯,爲了保證系統的可維護性。你能夠經過這種代理的方式,相似於spring的aop面向切面編程。靜態代理的侷限性每次都建立一個靜態代理類,假若有100個接口要代理,就要建立100個靜態代理類,很麻煩。直接經過java反射的方式去動態代理。java

建立一個要代理的接口spring

package com.cn.reflection;

/**
 * Created by ZC-16-012 on 2018/11/5.
 * 動態代理的接口
 */
public interface Person {
    void walk();
    void sayHello(String name);
}
package com.cn.reflection;


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

/**
 * Created by ZC-16-012 on 2018/11/5.
 */
public class MyInvoketionHandle implements InvocationHandler {

    /**
    * @param proxy 動態代理對象
     *@param method 表明正在執行的方法
    * @param args 表明調用目標方法時傳入的實參
    * */

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("---正在執行的方法:"+method);
        if (args!=null){
            System.out.println("下面是執行該方法時傳入的實參:");
            for (Object arg :args){
                System.out.println(arg);
            }
        }else {
            System.out.println("調用的方法沒有實參!");
        }
        return null;
    }
}
package com.cn.reflection;

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

/**
 * Created by ZC-16-012 on 2018/11/5.
 * 動態代理代碼測試
 */
public class ProxyTest {
    public static void main(String[] args){
        InvocationHandler handler= new MyInvoketionHandle();
        Person p= (Person) Proxy.newProxyInstance(Person.class.getClassLoader(),new Class[]{Person.class},handler);
        p.walk();
        p.sayHello("hello world");
    }
}

如圖運行結果以下:編程

 

能夠在invoke()去拓展功能了。ide

相關文章
相關標籤/搜索