Search code examples
javaclassloader

java dynamic classloader


how can I dynamically load a class in Java with two parameters which are the absolute filepath of the class file and the name of the method I wish to call?

eg path: c:\foo.class method: print()

I am just interested in the basics as a simple cmd line tool. A code example would b appreciated.

cheers hoax


Solution

  • Check out this example:

    // Create a File object on the root of the directory containing the class file
    File file = new File("c:\\myclasses\\");
    
    try {
        // Convert File to a URL
        URL url = file.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; MyClass.class should be located in
        // the directory file:/c:/myclasses/com/mycompany
        Class cls = cl.loadClass("com.mycompany.MyClass");
    } catch (MalformedURLException e) {
    } catch (ClassNotFoundException e) {
    }
    

    After this, you could do something like this to first create a new instace using the default constructor and invoking the method "print" without arguments:

    Object object = cls.newInstance();
    cls.getMethod("print").invoke(object);