你的位置:首页 > Java教程

[Java教程]利用反射加载类


反射: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