JAVA的動態代理分析

引導語:在使用動態代理類時,我們必須實現InvocationHandler接口,以下是本站小編分享給大家的JAVA動態代理,歡迎閱讀了解!

JAVA的動態代理分析

 1,被代理類 的接口 Proxied

Java代碼

package Test1;

// 被代理類 需實現的' 接口

public interface Proxied {

void doSomething();

void doSomethingElse(String str);

}

 2,一個 Proxied接口 的實現類(被代理類)

Java代碼

package Test1;

public class ConcreteProxied implements Proxied {

@Override

public void doSomething() {

try {

p(100);

} catch (InterruptedException e) {

tln("Error : InterruptedException");

}

tln(lass()impleName()

+ " >> doSomething .");

}

@Override

public void doSomethingElse(String str) {

try {

p(150);

} catch (InterruptedException e) {

tln("Error : InterruptedException");

}

tln(lass()impleName()

+ " >> doSomethingElse , argument = " + str + ".");

}

}

 3,TimingInvocationHandler 類,實現了 InvocationHandler 接口

Java代碼

package Test1;

import cationHandler;

import od;

public class TimeingInvocationHandler implements InvocationHandler{

//被代理的對象

private Object proxied;

public TimeingInvocationHandler(Object proxied){

ied = proxied;

}

// 參數 proxy 表示代理類的對象

// 參數 method 表示被代理類 和 代理類 都實現的接口 的方法對象

// 參數 args 表示方法 method 的參數數組

@Override

public Object invoke(Object proxy, Method method, Object[] args)

throws Throwable {

tln(eclaringClass()ame());

long currentTimeMillis = entTimeMillis();

Object ret = ke(proxied, args);

tln(lass()impleName()+" >> wastes time : "

+(entTimeMillis() - currentTimeMillis)+"ms");

return ret;

}

}

 4,測試類 Test

Java代碼

package Test1;

import y;

public class TestProxy {

public static void main(String[] args) {

Proxied proxied = new ConcreteProxied();

mething();

methingElse("only a String");

// 生成一個代理實例,這個代理實現了 Proxied 接口

// 對這個代理(proxy)的方法的調用 會 重定向到 TimeingInvocationHandler 的 invoke 方法

Proxied proxy = (Proxied) roxyInstance(s

lassLoader(), // 類加載器

new Class[] { s }, // 代理要實現的接口

new TimeingInvocationHandler(proxied) // 調用處理器

);

mething();

methingElse("only a String");

}

}

運行Test類,輸出如下:

ConcreteProxied >> doSomething .

ConcreteProxied >> doSomethingElse , argument = only a String.

ied

ConcreteProxied >> doSomething .

TimeingInvocationHandler >> wastes time : 110ms

ied

ConcreteProxied >> doSomethingElse , argument = only a String.

TimeingInvocationHandler >> wastes time : 156ms