jdk代理

jdk代理

    解釋:程序在運行過程中,根據被代理的接口來動態生成代理類的class文件,並且加載運行。
    JDK提供了java.lang.reflect.Proxy類來實現動態代理的,可通過它的newProxyInstance來獲得代理實現類。
1:自定義接口
package javabase.allinterface;

public interface SaySimple {
    
    void sayHelloForSomeone(String name);
    
}
2:接口實現類
package javabase.allimpl;

import javabase.allinterface.SaySimple;

public class SaySimpleImpl01 implements SaySimple{

    @Override
    public void sayHelloForSomeone(String name) {
        System.out.println("Hello!"+name);
    }

}
3:自定義實現InvocationHandler接口的類
package javabase;

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

public class ImplInvocationHandler implements InvocationHandler {
    
    private Object targetObj;
    
    public ImplInvocationHandler(Object obj) {
        this.targetObj = obj;
    }
    
    /**
     * @return
     * GY
     * 2017年11月6日
     */
    public Object getProxy(){
        return java.lang.reflect.Proxy.newProxyInstance(targetObj.getClass().getClassLoader(), 
                targetObj.getClass().getInterfaces(), 
                new ImplInvocationHandler(targetObj));
    }

    /*
     * 
     * 
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before invocation");
        Object retVal = method.invoke(targetObj, args);
        System.out.println("After invocation");
        return retVal; 
    }

}
4:測試,用代理對象執行被代理接口實現類的方法
package javabase;

import java.lang.reflect.Proxy;

import javabase.allimpl.SaySimpleImpl01;
import javabase.allinterface.SaySimple;

public class TestOfInvocationHandler {

    public static void main(String[] args) {
        SaySimple s = new SaySimpleImpl01();
        ImplInvocationHandler handle = new ImplInvocationHandler(s);
        
        SaySimple proxy = (SaySimple)Proxy.newProxyInstance(//TestOfInvocationHandler.class.getClassLoader(), 
                                                            handle.getClass().getClassLoader(),
                                                            //new Class[]{SaySimple.class},
                                                            s.getClass().getInterfaces(),
                                                            handle);
        proxy.sayHelloForSomeone("GY");
        
        SaySimple proxy2 = (SaySimple)handle.getProxy();
        proxy2.sayHelloForSomeone("WX");
    }

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章