#How can I create a dynamic class loader?

1 messages · Page 1 of 1 (latest)

junior peak
#

Here's my code:

package com.javadiscord.jdi.core.processor;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class DynamicClassLoader extends ClassLoader {
    private static final Logger LOGGER = LogManager.getLogger();
    private static final DynamicClassLoader INSTANCE = new DynamicClassLoader();
    private File file;

    private DynamicClassLoader() {}

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = loadClassData();
        if (classData == null) {
            throw new ClassNotFoundException("Class not found: " + name);
        }
        return defineClass(name, classData, 0, classData.length);
    }

    public void reloadFile(File newFile) {
        this.file = newFile;
    }

    private byte[] loadClassData() {
        try {
            return Files.readAllBytes(file.toPath());
        } catch (IOException e) {
            LOGGER.error(e);
            return null;
        }
    }

    public static DynamicClassLoader getInstance() {
        return INSTANCE;
    }
}```


I am using `Class<?> clazz = DynamicClassLoader.getInstance().loadClass(ClassFileUtil.getClassName(file));` to load a file however the changes are not being picked up. No errors, it's just not loading the updated file. 

Read online that I shouldn't mix ClassLoaders so I'm not. When a class loader loads a file, it's cached however my code is not doing that and I suspect somewhere it's still using the default class loader.

What am I doing wrong?
true zealotBOT
#

<@&987246399047479336> please have a look, thanks.

junior peak
#

it's more involved than i thought - have to preload the classes using this custom one to fix the issue