【问题标题】:How do I do the equivalent of getClassLoader().getResources() in an Eclipse plugin?如何在 Eclipse 插件中执行相当于 getClassLoader().getResources() 的操作?
【发布时间】:2012-11-16 15:33:04
【问题描述】:

我有一个IJavaProject,我需要在该项目的类路径中找到资源,即getClassLoader().getResources() 的等效项(注意:此调用返回Enumeration<URL> 而不是单个URL)。

如何从 Eclipse 包/插件中检查 Java 项目的类路径,例如查找包含 log4j.xml 的所有类路径条目?

【问题讨论】:

    标签: java eclipse plugins classpath


    【解决方案1】:

    使用getPackageFragmentRoots() 获取类路径中的条目的等效项。对于每个根,您可以调用getNonJavaResources() 来获取该根下的非Java 事物,并且您可以递归调用getChildren() 来获取孩子(以Java 层次结构的方式)。最终,那些间接遍历的子文件将是 java 源文件,您可以通过向它们发送 getUnderlyingResource() 方法来确认。

    这里有一些代码:

    private Collection<String> keys( IJavaProject project, String[] bundleNames ) throws CoreException, IOException {
    
        Set<String> keys = Sets.newLinkedHashSet();
    
        for( String bundleName : bundleNames ) {
    
            IPath path = new Path( toResourceName( bundleName ) );
    
            boolean found = false;
    
            IPackageFragmentRoot[] packageFragmentRoots = project.getPackageFragmentRoots();
            for( IPackageFragmentRoot root : packageFragmentRoots ) {
                found |= collectKeys( root, path, keys );
            }
    
            if( ! found ) {
                throw new BundleNotFoundException( bundleName );
            }
        }
    
        return keys;
    }
    
    private boolean collectKeys( IPackageFragmentRoot root, IPath path, Set<String> keys ) throws CoreException, IOException {
        IPath fullPath = root.getPath().append( path );
        System.out.println( "fullPath=" + fullPath );
    
        IFile file = root.getJavaProject().getProject().getFile( fullPath.removeFirstSegments( 1 ) );
        System.out.println( "file=" + fullPath );
    
        if( ! file.exists() ) {
            return false;
        }
    
        log.debug( "Loading " + file );
    
        InputStream stream = file.getContents( true );
        try {
            Properties p = load( file.getFullPath().toString(), stream );
    
            keys.addAll( keySet( p ) );
        } finally {
            stream.close();
        }
    
        return true;
    }
    
    protected String toResourceName( String bundleKey ) {
    
        String path = bundleKey.replace( '.', '/' );
        return path + ".properties";
    }
    

    【讨论】:

    • 如果您要查找的文件在文件系统上,它似乎可以工作。如果它在类路径上的 jar 中,我不知道你会以这种方式找到它。您可能必须在片段根目录上使用 getNonJavaResources()。
    • 啊,是的。当我谈到它时,我将更新代码以使用 JAR(它们将返回 IStorage 而不是 IFile)。
    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 2013-01-07
    • 2012-07-28
    • 1970-01-01
    • 2011-05-03
    • 2016-02-14
    • 2010-09-12
    • 1970-01-01
    相关资源
    最近更新 更多