如何使用两个参数动态装入Java中的类:类文件的绝对文件路径和要调用的方法的名称?
eg路径: c:\foo.class方法: print()
我只是感兴趣的基础知识作为一个简单的cmd线工具。如果有代码示例,我们将不胜感激。
欢呼恶作剧
发布于 2009-11-24 22:13:02
查看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) {
}在此之后,您可以这样做,首先使用默认构造函数创建一个新实例,并调用不带参数的"print“方法:
Object object = cls.newInstance();
cls.getMethod("print").invoke(object);发布于 2009-11-24 22:10:27
使用URLClassLoader。方法的名称无关紧要。您必须将包的根目录传递给类加载器。然后,您可以在Class.forName()中使用完全限定的类名(包+类名)来获取Class实例。您可以使用正常的反射调用来创建此类的实例,并对其调用方法。
为了让你的生活更简单,看看commons-beanutils吧。它使得调用方法变得更加简单。
https://stackoverflow.com/questions/1790289
复制相似问题