简体   繁体   中英

Reload class which is loaded using custom classloader

The following is my custom classloader class. I set this as default classloader with the following javaargs.

-Djava.system.class.loader=MyCustomClassLoader

import java.io.*;
public class MyCustomClassLoader extends ClassLoader { 
    public MyCustomClassLoader() { super(); } 
    public MyCustomClassLoader(ClassLoader parent) { super(parent); } 
    protected Class loadClass(String name, boolean resolve ) throws ClassNotFoundException { 
        Class c = super.loadClass(name, resolve ); 
        System.out.println( "name: " + name + ", class: " + c); 
        return c; 
    }
}

At this moment, all the classes are loaded with the above custom classloader class when I start server. I wish to update/reload class definition of classes that are part of a particular package (eg com.test) on demand. How can I do it?

You should make a class loader which will load custor classes by itself, dont let super load them. Try my example, it may help understand

package test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

class MyClassLoader extends ClassLoader {
    private Map<String, Class<?>> loadedClasses = new HashMap<>();
    private String dir;

    public MyClassLoader(String dir) throws MalformedURLException {
        this.dir = dir;
    }

    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> c = findLoadedClass(name);
        if (c != null) {
            return c;
        }
        c = loadedClasses.get(name);
        if (c != null) {
            return c;
        }
        try {
            String path = dir + name.replace(".","/") + ".class";
            byte[] bytes = Files.readAllBytes(Paths.get(path)); 
            c = defineClass(name, bytes, 0, bytes.length, null);
            if (resolve) {
                resolveClass(c);
            }
            return c;
        } catch (IOException ex) {
            return super.loadClass(name, resolve);
        }
    }
}

public class ChildFirstClassLoader {

    public static void main(String[] args) throws Exception {
        ClassLoader cl1 = new MyClassLoader("target/classes/");
        Object x1 = cl1.loadClass("test.X1").newInstance();
        System.out.println(x1.getClass().getClassLoader());
        cl1 = null;

        ClassLoader cl2 = new MyClassLoader("target/classes/");
        x1 = cl2.loadClass("test.X1").newInstance();
        System.out.println(x1.getClass().getClassLoader());

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM