Java ClassLoader
假如类不在classpath下,又想读取一个自定义的目录下的class,如果做呢?

读取自定义目录的类

示例读取c:/test/com/test.jdk/Key.class这个类。

  1. package com.test.jdk;
  2. public class Key {
  3. private String key = "111111";
  4. }

自定义ClassLoader

  1. import org.apache.commons.io.IOUtils;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. public class LocalClassLoader extends ClassLoader {
  6. private String path = "c:/test/";
  7. @Override
  8. protected Class<?> findClass(String name) throws ClassNotFoundException {
  9. Class<?> cls = findLoadedClass(name);
  10. if (cls != null) {
  11. return cls;
  12. }
  13. if (!name.endsWith(".Key")) {
  14. return super.loadClass(name);
  15. }
  16. try {
  17. InputStream is = new FileInputStream(path + name.replace(".", "/") + ".class");
  18. byte[] bytes = IOUtils.toByteArray(is);
  19. return defineClass(name, bytes, 0, bytes.length);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. return super.loadClass(name);
  24. }
  25. }

开始读取类

  1. public static void main(String[] args) {
  2. try {
  3. LocalClassLoader lcl = new LocalClassLoader();
  4. Class<?> cls = lcl.loadClass("com.test.jdk.Key");
  5. Field field = FieldUtils.getField(cls, "key", true);
  6. Object value = field.get(cls.newInstance());
  7. System.out.println(value);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }

自定义类加载器正常加载到类,程序最后输出:111111

URLClassLoader

上面自定义一个类加载器来读取自定义的目录,其实可以直接使用URLClassLoader就能读取,它已经实现了路径下类的读取逻辑。

  1. public static void main(String[] args) {
  2. try {
  3. URLClassLoader ucl = new URLClassLoader(new URL[]{new URL("c:/test/")});
  4. Class<?> cls = ucl.loadClass("com.test.jdk.Key");
  5. Field field = FieldUtils.getField(cls, "key", true);
  6. Object value = field.get(cls.newInstance());
  7. System.out.println(value);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }