Search code examples
javajarclassloader

Making a class loader


I am developing a class loader that will load plugins into my software. I have a jar file with two things in it, the package containing my code, and a text file containing the name of the class that I want to load from the jar. Is there a way for my app to read the text in the file and get the class name, then load the class with that name from the jar file?


Solution

  • This is the code that works:

    content = new Scanner(new File("plugins/" + listOfFiles[i].getName().replaceAll(".jar", "") + "/" + "plugin.cfg")).useDelimiter("\\Z").next();
    
    URL[] urls = null;
    try {
        File dir = new File("plugins/" + listOfFiles[i].getName());
        URL url = dir.toURL();
        urls = new URL[]{url};
    } catch (MalformedURLException e) {
    
    }
    
    try {
        ClassLoader cl = new URLClassLoader(urls);
        Class cls = cl.loadClass(content.replaceAll("Main-Class:", ""));
        Method enable = cls.getMethod("enable", (Class<?>[]) null);
        enable.invoke(enable, null);
    }catch (Exception e) {
        System.out.println("One of the installed plugins might have an invalid plugin.cfg.");
    }
    

    The code reads a file with the name of the main class in it, and then loads that class from the jar file it extracted earlier.