求助,動態代理模式的困惑

checkcode發表於2007-02-23
小弟最近在看動態代理的時候覺得有些奇怪

package bbb;

import java.lang.reflect.*;
import java.util.*;

public class Test implements java.lang.reflect.InvocationHandler {
	private Object ob;
	
	public Test(Object oo) {
		ob = oo;	
	}	
	
	public static Object factory(Object oo) {
		Class cls = oo.getClass();
		Object o = Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new Test(oo));
//		System.out.println(o.getClass()); //此處的對像是Proxy?????
		return o;	
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable 
	{
		//System.out.println("我讓代理了");	
		Object o = method.invoke(ob,args);

		return o;
	}
	
	public static void main(String args[]) throws Exception {
    	Object oo = factory(new TTT()); //如果factory是Proxy,如何轉型成Good?
    	System.out.println(oo.getClass().getName());
    	Proxy v = (Proxy)oo;
    	System.out.println(v);
    	Good f = (Good)v;
    	f.ff();
    }
}

interface Good {
	void ff();	
}

class TTT implements Good {
	public void ff() {}
}
	

<p class="indent">


我的問題是一個類並沒有實現一個介面卻能被轉型成那個介面請問這是如何實現的???

相關文章