Java动态加载类

前端之家收集整理的这篇文章主要介绍了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中

解决方法

我喜欢 the answer by Zellus中提到的ClassPathHacker类,但是它已经不再推荐使用了调用和坏习惯,所以这里是一个重写版本,它也缓存了Classloader和addUrl方法
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.IOException;
import java.io.File;

public class ClassPathHacker{

    private static final Class<URLClassLoader> URLCLASSLOADER =
        URLClassLoader.class;
    private static final Class<?>[] PARAMS = new Class[] { URL.class };

    public static void addFile(final String s) throws IOException{
        addFile(new File(s));
    }

    public static void addFile(final File f) throws IOException{
        addURL(f.toURI().toURL());
    }

    public static void addURL(final URL u) throws IOException{

        final URLClassLoader urlClassLoader = getUrlClassLoader();

        try{
            final Method method = getAddUrlMethod();
            method.setAccessible(true);
            method.invoke(urlClassLoader,new Object[] { u });
        } catch(final Exception e){
            throw new IOException(
                "Error,could not add URL to system classloader");
        }

    }

    private static Method getAddUrlMethod()
        throws NoSuchMethodException{
        if(addUrlMethod == null){
            addUrlMethod =
                URLCLASSLOADER.getDeclaredMethod("addURL",PARAMS);
        }
        return addUrlMethod;
    }

    private static URLClassLoader urlClassLoader;
    private static Method addUrlMethod;

    private static URLClassLoader getUrlClassLoader(){
        if(urlClassLoader == null){
            final ClassLoader sysloader = 
                ClassLoader.getSystemClassLoader();
            if(sysloader instanceof URLClassLoader){
                urlClassLoader = (URLClassLoader) sysloader;
            } else{
                throw new IllegalStateException(
                    "Not an UrlClassLoader: "
                    + sysloader);
            }
        }
        return urlClassLoader;
    }

}
原文链接:https://www.f2er.com/java/125779.html

猜你在找的Java相关文章