自定义ClassLoader

一、自定义类加载器代码:
package foo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyLocalClassLoader extends ClassLoader {

	private Log log = LogFactory.getLog(this.getClass());

	public MyLocalClassLoader() {
		super();
	}

	/* classes文件存放目录 */
	private String classesDir;

	public MyLocalClassLoader(String classesDir) {
		super();
		this.classesDir = classesDir;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {

		String classFileName = classesDir + File.separator + StringUtils.replaceChars(name, '.', File.separatorChar) + ".class";

		File classF = new File(classFileName);

		if (classF.exists()) {

			InputStream input = null;

			try {

				input = FileUtils.openInputStream(classF);

				byte[] b = IOUtils.toByteArray(input);

				return defineClass(name, b, 0, b.length);

			} catch (IOException e) {

				log.error(e.getMessage(), e);

			} finally {
				IOUtils.closeQuietly(input);
			}

		} else {
			log.error(classFileName + "文件不存在!");
		}

		return super.findClass(name);

	}

	protected void recursive_loadClass(boolean resolve) throws ClassNotFoundException {
		
		System.out.println("MyLocalClassLoader.recursive_loadClass()");
		
	}

}

测试:
package foo;

import java.lang.reflect.InvocationTargetException;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyLocalClassLoaderDemo {

	private static Log log = LogFactory.getLog(MyLocalClassLoaderDemo.class);

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,
			SecurityException, IllegalArgumentException, InvocationTargetException {

		ResourceBundle res = ResourceBundle.getBundle("foo/conf");

		Class<?> clazz = new MyLocalClassLoader(res.getString("classesDir")).loadClass("demo.ClassDemo");

		Object obj = clazz.newInstance();

		log.info(obj.toString());

		clazz = new MyLocalClassLoader(res.getString("classesDir")).loadClass("demo.Parent");
		clazz = new MyLocalClassLoader(res.getString("classesDir")).loadClass("demo.Child");

		obj = clazz.newInstance();

		Class<?>[] cc = {};
		Object[] oo = {};

		log.info(obj.getClass().getMethod("hello", cc).invoke(obj, oo));

	}

}

测试结果:
自定义ClassLoader
辅助测试类:
package demo;

public class ClassDemo {

	@Override
	public String toString() {
		
		return "ClassDemo.toString()";
		
	}

}

package demo;

public abstract class Parent {

	public String hello() {
		return "Parent.hello()";
	}
}

package demo;

public class Child extends Parent {

	@Override
	public String hello() {

		return "Child.hello()";

	}

}

你可能感兴趣的:(java,ClassLoader,自定义加载类)