public class Test { public void func() { System.out.println("func"); } 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(); */ } } |
Class<? extends Test> c = ((Test)obj).getClass(); c.newInstance().func(); |
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. |
public T newInstance() throws InstantiationException,IllegalAccessException |
Class c = ((Test)obj).getClass(); c.newInstance().func(); |
·Java初學者專區 | ·Java高級技術 | ||
·Java圖像與多媒體 | ·Java網絡編程 | ||
·Eclipse | ·Hibernate | ||
·Spring | ·Struts | ||
·Java設計模式 | ·EJB開發 |
原文轉自:http://www.anti-gravitydesign.com