请看下面的代码:
package interview; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Reflect { public static void main(String []args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException{ Class c = Class.forName("interview.Singleton"); //包名为interview Method m = c.getMethod("print"); //Sigleton有一个方法为print m.invoke(c.newInstance()); //调用print方法 } } Singleton类如下:
package interview; public class Singleton { private static Singleton inst = null; public static Singleton getInstance(){ if(inst == null){ inst = new Singleton(); } return inst; } public void print(){ System.out.println("i am singleton"); } } 运行之后将会输出:i am singleton