Java advanced advanced: custom ClassLoader

Java advanced advanced: custom ClassLoader

If our class is not in the classpath, and we want to read the class in a custom directory, what if we do?

Read the class of a custom directory

The example reads the class c:/test/com/test.jdk/Key.class.

package com.test.jdk;

public class Key {
    private String key = "111111";
}
 

Custom ClassLoader

import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LocalClassLoader extends ClassLoader {

    private String path = "c:/test/";

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> cls = findLoadedClass(name);
        if (cls != null) {
            return cls;
        }

        if (!name.endsWith(".Key")) {
            return super.loadClass(name);
        }

        try {
            InputStream is = new FileInputStream(path + name.replace(".", "/") + ".class");
            byte[] bytes = IOUtils.toByteArray(is);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.loadClass(name);
    }
}
 

Start reading class

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

The custom class loader is loaded into the class normally, the final output of the program: 111111

URLClassLoader

The above customize a class loader to read the custom directory, in fact, you can directly use the URLClassLoader to read it, it has realized the reading logic of the class under the path.

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

Pay attention to the WeChat official account of the Java technology stack, and reply in the background: java, get a Java technology tutorial compiled by the stack leader, including Java basics, multithreading, JVM, new features and more.

Scan the code to follow the official account, and Java dry goods will be pushed in time!