Java动态类加载器 [英] java dynamic classloader

查看:77
本文介绍了Java动态类加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中动态加载带有两个参数的类,这两个参数是类文件的绝对文件路径和我要调用的方法的名称?

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?

例如,路径:c:\foo.class
方法:print()

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

我只是对作为简单cmd线工具的基础知识感兴趣。

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

欢呼骗局

推荐答案

检查出此示例

// 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:

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

这篇关于Java动态类加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆