java dynamic classloader

柔情痞子 提交于 2019-12-11 12:52:14

问题


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


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/1790289/java-dynamic-classloader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!