Search code examples
javaclasspathclassloader

Load and instantiate class from jar in class search path


I am looking for a way to instantiate an object from a jar file in my class search path, i know the name of the class and the parent class it extends and the interface it implements, unfortunatelly i have not been able to find a solution so far. So, suppose the following:

interface Modifier{
 //is basically just a flag
}

Then:

public class ModifierImpl implements Modifier{
 //some methods
}

Then:

public class CustomModifierImpl extends ModifierImpl{
    //some implementation here
    }

Those interfaces/classes are into a jar that i import dinamically in my project and then i would like to instantiate an instance of CustomModifierImpl

Since i know that the class Class is generic, i thought that something like so would be possible, but its not:

private Class<ModifierImpl> loadClass(String fullClassName) {
    Class<ModifierImpl> clazz;
    try {
        clazz= urlLoader.loadClass(fullClassName);
    } catch (ClassNotFoundException e) {
        return null;
    }
    return clazz;
}

I get a type mismatch when i do this, is there any other way i can achieve this? i would not like to work with an instance of Class<?> all around my program as i would probably need to do dozens of casts.

This will also not work:

private Class<ModifierImpl> loadClass(String fullClassName) {
    Class<ModifierImpl> clazz;
    try {
        clazz= urlLoader.loadClass(fullClassName).cast(clazz);
    } catch (ClassNotFoundException e) {
        return null;
    }
    return clazz;
}

Thank you


Solution

  • to load class from .class file

    File file2 = new File  ("c:\\myclasses\\");
    
    // Convert File to a URL
    URL url = file2.toURL();          // file:/c:/myclasses/
     URL[] urls = new URL[]{url};
    
    // Create a new class loader with the directory
    ClassLoader cl = new URLClassLoader(urls);
    
     // Load in the class; 
     Class cls = cl.loadClass("test.MyClass");
    

    to get the class:

    Class aClass;
    ClassLoader classLoader = test.class.getClassLoader();
    try {
        aClass = classLoader.loadClass(fullClassName);
       } catch (ClassNotFoundException e) {
       e.printStackTrace();
     }
    

    once you have the class, you can instantiate it:

    Class<?> clazz = Class.forName(fullClassName);
    Constructor<?> constructor = clazz.getConstructor();
    Object result = constructor.newInstance();