package com.axis.innovators.box.plugins;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 自定义加载器
 * @author tzdwindows 7
 */
public class BoxClassLoader extends URLClassLoader {

    public BoxClassLoader(ClassLoader parent) {
        super(new URL[0], parent);
    }

    public BoxClassLoader(URL[] sources) {
        super(sources);
    }

    public BoxClassLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classBytes;
        try {
            classBytes = getClassBytes(name);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] transformedClass = transformClass(name, null, classBytes);
        return defineClass(name, transformedClass, 0, transformedClass.length);
    }

    public byte[] getClassBytes(String className) throws IOException, ClassNotFoundException {
        String path = className.replace('.', '/') + ".class";
        URL classUrl = getResource(path);
        if (classUrl == null) {
            throw new ClassNotFoundException("Class not found: " + className);
        }
        try (InputStream is = classUrl.openStream()) {
            return is.readAllBytes();
        }
    }

    public byte[] transformClass(String className, String transformedName, byte[] basicClass) {
        return PluginLoader.transformClass(className, transformedName, basicClass);
    }
}
