2017-05-16 48 views
0

我在這裏得到這個代碼在堆棧溢出。這是一個好的,但只適用於Netbeans。生成.jar文件後,不再工作,不要給我錯誤消息。包裝後反射不起作用

/** 
* Scans all classes accessible from the context class loader which belong 
* to the given package and subpackages. 
* 
* @param packageName The base package 
* @return The classes 
* @throws ClassNotFoundException 
* @throws IOException 
*/ 
public Class[] getClasses(String packageName) 
     throws ClassNotFoundException, IOException { 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
    assert classLoader != null; 
    String path = packageName.replace('.', '/'); 
    Enumeration<URL> resources = classLoader.getResources(path); 
    List<File> dirs = new ArrayList<File>(); 
    while (resources.hasMoreElements()) { 
     URL resource = resources.nextElement(); 
     dirs.add(new File(resource.getFile())); 
    } 
    ArrayList<Class> classes = new ArrayList<Class>(); 
    for (File directory : dirs) { 
     classes.addAll(findClasses(directory, packageName)); 
    } 
    return classes.toArray(new Class[classes.size()]); 
} 

/** 
* Recursive method used to find all classes in a given directory and 
* subdirs. 
* 
* @param directory The base directory 
* @param packageName The package name for classes found inside the base 
* directory 
* @return The classes 
* @throws ClassNotFoundException 
*/ 
private List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException { 
    List<Class> classes = new ArrayList<Class>(); 
    if (!directory.exists()) { 
     return classes; 
    } 
    File[] files = directory.listFiles(); 
    for (File file : files) { 
     if (file.isDirectory()) { 
      assert !file.getName().contains("."); 
      classes.addAll(findClasses(file, packageName + "." + file.getName())); 
     } else if (file.getName().endsWith(".class")) { 
      classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); 
     } 
    } 
    return classes; 
} 

這段代碼封裝在另一個項目中,用作我的JMenu庫。但只適用於netbeans。我不明白爲什麼。

更新

我會盡量解釋更好。

我有一個項目與JMenu一起工作,通過反射來讀取其他項目中的類。這個項目將用作其他項目的圖書館。當它在netbeans上運行的時候表現不錯,但是當生成.jar文件不再工作時,我不會收到任何錯誤消息。

+1

你的意思做「不工作了」?它會崩潰嗎?它表現出意外嗎? – Michael

+0

我沒有收到錯誤。該代碼只是無所事事。 – Krismorte

回答