动态加载java类文件的方法 [英] Method to dynamically load java class files

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

问题描述

什么是动态加载java类文件的好方法,以便编译成jar的程序可以读取目录中的所有类文件并使用它们,以及如何编写文件以使它们具有必要的包

我相信这是一个 ClassLoader



我建议您从下面的示例开始,加载不在类路径中的类文件。

  //在包含类文件的目录的根目录上创建一个File对象
文件file = new File(c:\\myclasses \\);

try {
//将文件转换为URL
URL url = file.toURL(); // file:/ c:/ myclasses /
URL [] urls = new URL [] {url};

//使用目录
创建一个新的类加载器classLoader cl = new URLClassLoader(urls);

//加载类; MyClass.class应该位于
//目录文件:/ c:/ myclasses / com / mycompany
Class cls = cl.loadClass(com.mycompany.MyClass);
} catch(MalformedURLException e){
} catch(ClassNotFoundException e){
}


What would be a good way to dynamically load java class files so that a program compiled into a jar can read all the class files in a directory and use them, and how can one write the files so that they have the necessary package name in relation to the jar?

解决方案

I believe it's a ClassLoader you're after.

I suggest you start by looking at the example below which loads class files that are not on the class path.

// 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) {
}

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

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