package com.thinker.common.classloader;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;

/**
 * @author lzh
 */
public class HotSwapClassLoader extends URLClassLoader {
    public HotSwapClassLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
    }

    public HotSwapClassLoader(URL[] urls) {
        super(urls);
    }

    public HotSwapClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
        super(urls, parent, factory);
    }
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name,false);
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        if(null != super.findLoadedClass(name)) reload(name, resolve);
        Class<?> clazz = super.findClass(name);
        if(resolve) super.resolveClass(clazz);
        return clazz;
    }

    public Class<?> reload(String name ,boolean resolve) throws ClassNotFoundException{
        return new HotSwapClassLoader(super.getURLs(), super.getParent()).loadClass(name, resolve);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
    }
}
