Java动态加载类 [英] Java Dynamically Loading a class

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

问题描述

我正在尝试将类动态加载到组件中。我正在使用文件选择器来选择要加载的.JAR文件,然后选择一个选项窗格来获取类的名称。



我已经拖网了如何将java文件转换为URL,以便将其加载到URLClassLoader中,我已经提出:

  File myFile = filechooser.getSelectedFile(); 
String className = JOptionPane.showInputDialog(
this,Class Name,Class Name,JOptionPane.QUESTION_MESSAGE);

URL myUrl = null;
try {
myUrl = myFile.toURL();
} catch(MalformedURLException e){
}

URLClassLoader loader = new URLClassLoader(myUrl);
loader.loadClass(className);

我现在收到一个'找不到符号'错误,将URL加载到URLClassLoader

解决方案

URLClassLoader的构造函数需要一组URL ,而不是一个URL。


I am attempting to load classes dynamically into a component. I am using a file chooser to select the .JAR file that will be loaded and then a option pane to get the name of the class.

I have trawled the internet looking for how to convert a java file to a URL in order to load it in URLClassLoader and I have come up with:

File myFile = filechooser.getSelectedFile();
String className = JOptionPane.showInputDialog(
    this, "Class Name:", "Class Name", JOptionPane.QUESTION_MESSAGE);

URL myUrl= null;
try {
    myUrl = myFile.toURL();
} catch (MalformedURLException e) {
}

URLClassLoader loader = new URLClassLoader(myUrl);
loader.loadClass(className);

I am now getting a 'cannot find symbol' error for loading the URL into the URLClassLoader

解决方案

The constructor of URLClassLoader takes an array of URLs, not a single URL.

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

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