bgu*_*uiz 10 java reflection jar classpath package
关于如何找到当前类路径中存在的包名列表的任何建议?
这需要在运行时通过类路径上加载(和执行)的一个类(即从里到外,而不是在外面)以编程方式完成.
更多细节:
我考虑的一种方法是对类加载器到目前为止加载的每个类使用反射,并从中提取包名.但是,我的应用程序已经遇到了数千个类,所以我需要一个更有效的方法.
我考虑的另一件事是类似于找出类路径中的JAR文件,然后为每个JAR并行执行目录列表.但是,我不知道这是否可以从应用程序/如何做到这一点.
奖励积分
任何建议可以按顶级包过滤的方式的人都可以获得奖励积分.例如,显示所有包含在com.xyz==> 下的包com.xyz.*,com.xyz.*.*
谢谢!
如果你确实需要挂载和扫描jar文件,那么vfs就会内置它.如果你必须走这条路,这可能会让事情变得容易一些.
编辑#1:您可以像这样获取类路径(来自此处的示例):
String strClassPath = System.getProperty("java.class.path");
System.out.println("Classpath is " + strClassPath);
Run Code Online (Sandbox Code Playgroud)
从那里你可以看到本地文件系统类,jar等.
编辑#2:这是VFS的解决方案:
import java.util.HashSet;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.VFS;
public class PackageLister {
private static HashSet< String > packageNames = new HashSet< String >();
private static String localFilePath;
/**
* @param args
* @throws Throwable
*/
public static void main( final String[] args ) throws Throwable {
FileSystemManager fileSystemManager = VFS.getManager();
String[] pathElements = System.getProperty( "java.class.path" ).split( ";" );
for( String element : pathElements ) {
if ( element.endsWith( "jar" ) ) {
FileObject fileObject = fileSystemManager.resolveFile( "jar://" + element );
addPackages( fileObject );
}
else {
FileObject fileObject = fileSystemManager.resolveFile( element );
localFilePath = fileObject.getName().getPath();
addPackages( fileObject );
}
}
for( String name : packageNames ) {
System.out.println( name );
}
}
private static void addPackages( final FileObject fileObject ) throws Throwable {
FileObject[] children = fileObject.getChildren();
for( FileObject child : children ) {
if ( !child.getName().getBaseName().equals( "META-INF" ) ) {
if ( child.getType() == FileType.FOLDER ) {
addPackages( child );
}
else if ( child.getName().getExtension().equals( "class" ) ) {
String parentPath = child.getParent().getName().getPath();
parentPath = StringUtils.remove( parentPath, localFilePath );
parentPath = StringUtils.removeStart( parentPath, "/" );
parentPath = parentPath.replaceAll( "/", "." );
packageNames.add( parentPath );
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5588 次 |
| 最近记录: |