這兩天對java的動態代理感興趣,自己寫了個最簡單的代碼,認識一下動態代理!
例子:
類列表:
MyObjec是執行類。
MyProxy 是我自己實現的動態代理類,這個類實現了InvocationHandler接口,關於這個藉口的描述就不多說了,可以參照api文檔!好像動態代理類都實現這個接口,我是這麼理解的,呵呵!
Test 類是我的業務類
ITest 是我業務類的接口!
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyObject {
public static void main(String[] args) {
ITest test = new Test("kimi");
ITest t = new MyProxy().getProxy(test);
t.outPut();
}
}
class MyProxy implements InvocationHandler {
private ITest itest = null;
private Object test = null;
public synchronized ITest getProxy(Object o) {//用Factory的方式取代理實例,不知道做得對不對
if (itest == null) {
test = o;
itest = (ITest) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
o.getClass().getInterfaces(),
this);
return itest;
} else
return itest;
}
public Object invoke(Object o, Method m, Object[] aguments) throws Throwable {
System.out.println("my Proxy start ok!!!");
return m.invoke(
test,
aguments);
}
}
class Test implements ITest {
private String name = null;
public Test(String name) {
this.name = name;
}
public void outPut() {
System.out.println("my Test start ok!!!" + String.format("%n") + "my name is :" + this.name);
}
}
interface ITest {
public void outPut();
}
最後,如有不妥當之處,請指示~!謝謝