簡體   English   中英

從jar加載一個類

[英]Load a class from a jar

我正在嘗試從jar加載一個類,我正在使用classLoader。

我有這部分代碼用於准備classLoader:

private void loadClass(){

    try{
        JarFile jarFile = new JarFile( Path);
        Enumeration e = jarFile.entries();

        URL[] urls = { new URL("jar:file:" + Path +"!/") };
        classLoader = URLClassLoader.newInstance(urls);


    } catch (MalformedURLException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

現在我加載一個類,然后嘗試獲取一個新實例

....           
           loadClass();

           Class device = classLoader.loadClass( "org.myPackage.MyClass");

           MyMotherClass Device = ( MyMotherClass) device.newInstance();
...

MyClass擴展了MyMotherClass,當我執行classLoader.loadClass(“org.myPackage.MyClass”)時,MyMotherClass位於classLoader中。 此刻,沒事。

現在,在device.newInstance()中,我得到一個例外。 問題是MyClass使用的其他類不在類路徑中。

我能做什么?

我有另一個方法,在classLoader中加載所有需要的類,但是當我得到新實例時不起作用。 我不能改變MyClass和其他人

這是我用來在運行時動態加載jar的一些代碼。 我利用反射來規避你不應該這樣做的事實 (也就是說,在JVM啟動后修改類路徑)。 只需將my.proprietary.exception更改為合理的內容即可。

    /*
     * Adds the supplied library to java.class.path.
     * This is benign if the library is already loaded.
     */
    public static synchronized void loadLibrary(java.io.File jar) throws my.proprietary.exception
    {
        try {
            /*We are using reflection here to circumvent encapsulation; addURL is not public*/
            java.net.URLClassLoader loader = (java.net.URLClassLoader)ClassLoader.getSystemClassLoader();
            java.net.URL url = jar.toURI().toURL();
            /*Disallow if already loaded*/
            for (java.net.URL it : java.util.Arrays.asList(loader.getURLs())){
                if (it.equals(url)){
                    return;
                }
            }
            java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
            method.setAccessible(true); /*promote the method to public access*/
            method.invoke(loader, new Object[]{url});
        } catch (final NoSuchMethodException | 
            java.lang.IllegalAccessException | 
            java.net.MalformedURLException | 
            java.lang.reflect.InvocationTargetException e){
            throw new my.proprietary.exception(e.getMessage());
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM