package control;

import java.io.*;
import java.net.*;
import java.util.regex.Pattern;

/**
 * Hilfsklasse, um Algorithmen-Classen dynamisch nachladen zu können und 
 * aktualisierte Class-Dateien während der Laufzeit erneut laden zu können.
 * 
 * @author Schaller (nach http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html)
 * @version 16.02.2021
 */
public class MyClassLoader extends ClassLoader{

    public MyClassLoader(ClassLoader parent) {
        super(parent);
    }

    public Class loadClass(String name) throws ClassNotFoundException {
        if(!name.contains("GraphAlgo_"))
                return super.loadClass(name);

        try {
      
                
            URL myUrl = new URL("file:"+name.split(Pattern.quote("."))[0]+"/"+name.split(Pattern.quote("."))[1]+".class");
            URLConnection connection = myUrl.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();

            while(data != -1){
                buffer.write(data);
                data = input.read();
            }

            input.close();

            byte[] classData = buffer.toByteArray();

            return defineClass(name, classData, 0, classData.length);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}