Java class loading and reflection


public class Reflect {

	public static Car initCar() throws Throwable{
		String className = "mycollection.Car";
		
		//load Class(byte code) into JVM Memory
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		Class<?> clazz = cl.loadClass(className);
		
		/**
		 * Delegated mechanism for class loading based on security considerations to avoid system library files from being replaced by mistake (.class bytecode),
		 * First, it will load the core class library of jre from ClassLoader (root class loader)
		 * ExtClassLoader (loads the Jar package in ext)
		 * AppClassLoader (application class loading is responsible for loading classes under Classpath)
		 */
		System.out.println("Current class loader: "+cl);
		System.out.println("Parent Loader:"+cl.getParent());
		System.out.println("Grandfather Loader"+cl.getParent().getParent());
		
		//init a Obj
		Constructor<?> cons = clazz.getDeclaredConstructor((Class[])null);
		Car car = (Car) cons.newInstance();
		
		//reflect method and set attributes
		Method setBrand = clazz.getMethod("setBrand", String.class);
		setBrand.invoke(car, "夏利");
		Method setColor = clazz.getMethod("setColor", String.class);
		setColor.invoke(car, "蓝色");
		Method setMaxSpeed = clazz.getMethod("setMaxSpeed", String.class);
		setMaxSpeed.invoke(car, "110");
		
		return car;
		
	}
	
	public static void main(String ...args) throws Throwable{
		Car initCar = initCar();
		System.out.println(initCar.getBrand());
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326154304&siteId=291194637