反射:java.lang.reflect
要被加載的類:
package eg.fortest; public class WaitingforLoader { private String str; static{ System.out.println("loading WaitingforLoader"); } public WaitingforLoader() { str="empty"; System.out.println("Constructor of WaitingforLoader without anything."); } public WaitingforLoader(String str) { this.str=str; System.out.println("Constructor of WaitingforLoader with "+str); } public void getStr(int i){ System.out.println("str="+str); } }
加載運行的類:
package factory.classfactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; //import eg.fortest.WaitingforLoader;不需要這條語句 public class LoadMyClass { public static void main(String[] args) throws ClassNotFoundException, InstantiationException,IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { System.out.println("Program start."); /** * 類的加載、鏈接、初始化。 */ Class<?> clazz = Class.forName("eg.fortest.WaitingforLoader"); /** * 對象的創建 */ Object myvar1 = clazz.newInstance(); Constructor cor=clazz.getConstructor(String.class); Object myvar2 =cor.newInstance("string Parameter"); /** * 方法調用 */ Method m =clazz.getMethod("getStr",int.class); m.invoke(myvar2, 1); } }
輸出的結果:
Program start.
loading WaitingforLoader
Constructor of WaitingforLoader without anything.
Constructor of WaitingforLoader with string Parameter
str=string Parameter