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(); |