2016-02-22 82 views
1

我需要在运行时加载一个jar文件在Java中,我有这个代码,但它不加载任何jar,我不知道如何,有人可以告诉我为什么?我有JVM 8和NetBeans 8,目的是创建一个程序,可以将jar文件作为Windows的插件加载。Java类路径和类加载

package prueba.de.classpath; 
import java.io.File; 
import java.lang.reflect.Method; 
import java.net.URL; 
import java.net.URLClassLoader; 

public class PruebaDeClasspath { 

    public static void main(String[] args) { 
     try { 
      Class.forName("PluginNumeroUno"); 
     } catch (ClassNotFoundException e) { 
      System.out.println("Not Found"); 
     } 

     try { 
      URLClassLoader classLoader = ((URLClassLoader) ClassLoader 
        .getSystemClassLoader()); 
      Method metodoAdd = URLClassLoader.class.getDeclaredMethod("addURL", 
        new Class[]{URL.class}); 
      metodoAdd.setAccessible(true); 


      File file = new File("plugins/PrimerPlugins.jar"); 

      URL url = file.toURI().toURL(); 
      System.out.println(url.toURI().toURL()); 

      metodoAdd.invoke(classLoader, new Object[]{url}); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     try { 
      Class.forName("PluginNumeroUno"); 
      System.out.println("ok"); 
     } catch (ClassNotFoundException e) { 
      System.out.println("Not Found"); 
     } 

    } 

} 
+1

在问题 – flakes

+1

中提供您当前的System.out控制台输出我感觉您在这里重新发明了方向盘。到底为什么你需要手动加载jar文件? 'java --classpath'没有这个把戏吗? – Tobb

回答

1

尝试创建新的类加载器而不是转换系统类加载器。

删除此行:

URLClassLoader classLoader = ((URLClassLoader) ClassLoader.getSystemClassLoader()); 

,并创建新的装载机和如下使用它:

File file = new File("plugins/PrimerPlugins.jar"); 
URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()},  
    PruebaDeClasspath.class.getClassLoader()); 
Class.forName("prueba.de.classpath.PluginNumeroUno", true, classLoader); //fully qualified! 

请注意,要加载的类名必须是完全合格的。你也不必动态强制addURL()公开。