public class Test { public void func() { System.out. }
public static void main(String args[]) throws Exception { Object obj = new Test(); //下面這行可以成功編譯 ((Test)obj).getClass().newInstance().func();
//下面這兩行無法通過編譯 /*Class c = ((Test)obj).getClass(); c.newInstance().func(); */ } } 感謝paulex先生的幫助,在paulex先生的提示下,我基本上明白了上述問題的原因。下面是paulex先生的解答:
因為Generic, 編譯器可以在編譯期獲得類型信息所以可以編譯這類代碼。你將下面那兩行改成
Class<? extends Test> c = ((Test)obj).getClass(); c.newInstance().func(); 應(yīng)該就能通過編譯了。
下面是我在paulex先生解答的基礎(chǔ)上,對問題的進(jìn)一步解釋:
在JDK 1.5中引入范型后,Object.getClass()方法的定義如下:
public final Class<? extends Object> getClass() Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Returns: The java.lang.Class object that represents the runtime class of the object. The result is of type Class<? extends X> where X is the erasure of the static type of the eXPression on which getClass is called. 這說明((Test)obj).getClass()語句返回的對象類型為Class<? extends Test>,而Class<T>的newInstance()方法的定義如下:
public T newInstance() throws InstantiationException,IllegalaccessException 即對于編譯器看來,Class<Test>的newInstance()方法的對象類型為Test,而((Test)obj).getClass()返回的為對象類型為Class<? extends Test>,所以,編譯器認(rèn)為((Test)obj).getClass().newInstance()返回的對象類型為Test。
下面這兩行代碼之所以無法通過編譯
Class c = ((Test)obj).getClass(); c.newInstance().func(); 是因為((Test)obj).getClass()返回的為對象類型為Class<? extends Test>,但是我們在第一行將結(jié)果強制轉(zhuǎn)換成了Class,然后再去調(diào)用Class的newInstance方法,而不是去調(diào)用Class<Test>的newInstance方法,編譯器當(dāng)然不再認(rèn)為Class的newInstance方法返回的對象為Test了。進(jìn)入討論組討論。