簡體   English   中英

包裝后反射不起作用

[英]Reflection doesn't work after packing

我在堆棧溢出這里得到此代碼。 這是一個很好的選擇,但僅適用於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文件不再起作用時,我也沒有收到任何錯誤消息。

當所有資源打包在一個jar中時,不再有文件。

而是使用this.class.getResource()this.class.getResourceAsStream()

或者,您可以使用一些庫,請參見可以使用反射找到包中的所有類嗎?

暫無
暫無

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

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