views:

186

answers:

2

hi

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

+5  A: 

Use URLClassLoader. The name of the method is irrelevant. You must pass the root directory of your package to the class loader. Then you can use the fully qualified class name (package + class name) in Class.forName() to get the Class instance. You can use the normal reflection calls to create an instance of this class and call methods on it.

To make your life more simple, have a look at commons-beanutils. It makes invoking methods much more simple.

Aaron Digulla
+2  A: 

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);
Tim Büthe