类发现,反射,jar和jnlp

时间:2011-01-05 17:47:33

标签: java reflection jar java-web-start

在我们的系统中,我们有一个插件机制,允许我们在运行时实现未知的类。

在类路径中提供了目录或jar,系统能够探索包含的类,如果类实现了特定的接口,它可以实例化并用作插件。

所有东西都打包成罐子,效果很好。但是,当尝试将其捆绑为webstart应用程序时,这种机制似乎已经破裂。

更具体地说,似乎发现类不再起作用了:

public static Collection<String> getAllClassFiles()
{
    Collection<String> all_files = new ArrayList<String>();

    String pathSep = System.getProperty("path.separator");
    String classpath = System.getProperty("java.class.path");

    for (String path : classpath.split(pathSep))
    {
        File filepath = new File(path);

        if (filepath.isDirectory()) 
        {
            all_files.addAll(dirContent(filepath));
        } 
        else if (path.endsWith(".jar")) 
        {

            JarFile jar;
            try {
                jar = new JarFile(filepath);
            } 
            catch (IOException e) {
                Log.warning("WARNING: " + filepath + " could not be opened!");
                continue;
            }

            for (Enumeration<JarEntry> entries = jar.entries(); entries
                    .hasMoreElements();)
            {
                JarEntry entry = entries.nextElement();
                if (entry.getName().endsWith(".class"))
                    all_files.add(entry.getName());
            }
        } 
        else if (path.endsWith(".class")) {
            all_files.add(path);
        } 
        else {
            Log.warning("Warning: corrupt classpath entry: " + path);
        }

    }
    return all_files;
}

所以...当使用罐子直接调用系统时这是有效的...但是不管webstart是什么,尽管所有罐子都已签名并包含在内。

知道如何让它与webstart一起使用吗?

1 个答案:

答案 0 :(得分:0)

可能通过获取上下文类加载器并尝试获取其URL [] s然后通过内容进行流式传输而获得幸运。

我认为这也不是一个好主意。 Java并非以这种方式反映内容。但是,提供的可能不那么优雅,是读取元数据文件的可能性,例如使用Thread.getContextClassLoader().getResources("META-INF/plugins.txt"),您可以在其中定义要实例化的类。

或者,更精简,使用ServiceLoader。

取决于你的claspath和jar,无论如何,这比加速每个班级的加载更快......