tinycodinglm / lang /lang-0042.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.84 kB
opencode trace
System You are an expert Java developer specializing in reflection, dynamic class loading, and modern Java APIs for runtime introspection.

You are an expert Java developer specializing in reflection, dynamic class loading, and modern Java APIs for runtime introspection.

User

Create a custom ClassLoader from scratch. Show how to override findClass, defineClass, and handle class loading from a byte array. Include a complete working example.

Assistant

Here is a complete custom ClassLoader that loads classes from byte arrays.

java
import java.nio.file.*;
import java.util.*;

public class CustomClassLoader extends ClassLoader {
    private final Map<String, Class<?>> classCache = new java.util.concurrent.ConcurrentHashMap<>();
    private final Path classPath;
    public CustomClassLoader(Path classPath, ClassLoader parent) { super(parent); this.classPath = classPath; }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if (classCache.containsKey(name)) return classCache.get(name);
        try { return super.findClass(name); } catch (ClassNotFoundException e) { }
        String fileName = name.replace('.', java.io.File.separatorChar) + ".class";
        try {
            Path classFile = classPath.resolve(fileName);
            byte[] classBytes = java.nio.file.Files.readAllBytes(classFile);
            return defineClass(name, classBytes, 0, classBytes.length);
        } catch (java.io.IOException e) { throw new ClassNotFoundException("Could not load class: " + name, e); }
    }
    public void loadClassFromBytes(String name, byte[] bytes) {
        Class<?> clazz = defineClass(name, bytes, 0, bytes.length);
        classCache.put(name, clazz);
    }
    public static void main(String[] args) throws Exception {
        Path currentDir = Paths.get(".");
        CustomClassLoader loader = new CustomClassLoader(currentDir, ClassLoader.getSystemClassLoader());
        String className = "com.example.MyClass";
        try {
            Class<?> clazz = loader.loadClass(className);
            System.out.println("Loaded: " + clazz.getName());
            System.out.println("ClassLoader: " + clazz.getClassLoader());
        } catch (ClassNotFoundException e) { System.out.println("Class not found: " + e.getMessage()); }
    }
}

Key concepts: findClass is called by loadClass after parent delegation fails. defineClass converts a byte array to a Class object. You can override loadClass for full control over delegation. Class caching prevents re-loading the same class. Custom ClassLoaders are essential for hot-reloading and plugin systems.