我需要扫描实现或扩展特定类的类或jar文件。
这与Eclipse用来扫描插件的机制是一样的。 有一种方法可以做到这一点?Java中的扫描类或jar文件
回答
从exmaple depot: How to load a Class that is not on the classpath:
// Create a File object on the root of the directory
// containing the class file
File file = new File("c:\\class\\");
try {
// Convert File to a URL
URL url = file.toURL(); // file:/c:/class/
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
ClassLoader loader = new URLClassLoader(urls);
// Load in the class; Class.childclass should be located in
// the directory file:/c:/class/user/information
Class cls = loader.loadClass("user.informatin.Class");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}
列入目录中的文件,如果有必要,使用File.list()
。
加载类时,可以通过执行clazz.isInstance
来检查它是否实现了特定的接口。从文档:
确定指定的Object是否与此Class表示的对象分配兼容。这种方法是动态的相当于Java语言instanceof运算符。
从一个jar文件加载类:
How to load a jar file at runtime
要在jar文件中列出的文件:JarFile.entries()
。
我如何加载这个特定的类? 我扫描它,但然后我还需要加载它,只有当它实现了一个特定的接口。 – enfix 2010-05-25 08:41:37
@enfix:首先你加载它然后你扫描它,如果它符合你的要求使用它,否则扔它。 – 2010-05-25 10:08:36
您可以通过使用字节码解析器(如ASM或BCEL)对其进行扫描而无需进行类加载。随着ASM ...
byte[] bytecode = [read bytes from class or jar file];
ClassReader reader = new ClassReader(bytecode);
String[] interfaces = reader.getInterfaces();
- 1. Spring组件从jar中扫描类?
- 2. 从jar文件中扫描注释
- 3. 春天 - 扫描特定的jar文件
- 4. 扫描.class文件或JAR文件,以反映
- 5. java中的扫描器类
- 6. Java扫描文本文件
- 7. Java扫描器类
- 8. Java扫描器类
- 9. 扫描仪类Java
- 10. Java扫描仪文件
- 11. JarScan扫描所有子文件夹中的特定类的所有JAR文件
- 12. 不要加载/扫描来自特定jar的类文件
- 13. HackerRank扫描器类的Java
- 14. JAVA +扫描文档
- 15. BufferedReader或扫描仪? (Java)
- 16. 如何在Java中扫描文件夹?
- 17. Java扫描仪从文件中读取
- 18. 如何在Java中扫描文件夹?
- 19. 扫描,扫描仪类
- 20. Java类和扫描器
- 21. java - 扫描仪类NoSuchElementFoundException
- 22. 最后一行输入不在Java扫描器类中扫描
- 23. 使用Java扫描文本文件
- 24. 程序不扫描文本文件(Java)
- 25. Haxe中Java扫描器类的等效
- 26. 使用扫描仪扫描txt文件
- 27. 扫描类似INI的大文件
- 28. 的Java:没有这样的文件或目录(使用扫描器类)
- 29. 扫描文件夹中的文件
- 30. 从文件中扫描C
有办法,但你不应该需要它;) – Bozho 2010-05-25 08:34:50
@Bozho:为什么不呢?别告诉我你可以闻到它;)。 – 2010-05-25 08:38:02