[英]Get the Class objects for all classes in the module java.base
How can I get the Class
objects for all the classes in the module java.base
programmatically?如何以编程方式获取模块
java.base
所有类的Class
对象? I'm open to using any external libraries.我愿意使用任何外部库。 I have looked at the Reflections library but could not get a list of classes in the built-in Java Library, only classes on the classpath.
我查看了Reflections库,但无法获取内置 Java 库中的类列表,只能获取类路径中的类。 I tried to manually do this by iterating through all the files in my file system, but (as far as I'm aware) I cannot get to the classes because they are inside a jar file.
我试图通过遍历文件系统中的所有文件来手动执行此操作,但是(据我所知)我无法访问这些类,因为它们位于 jar 文件中。 What would the code look like for getting all the
Class
objects for the classes in java.base
?获取
java.base
类的所有Class
对象的代码是什么样的?
Thanks.谢谢。
I was able to extract all of the classes from the src.zip file:我能够从 src.zip 文件中提取所有类:
public class TypeUtils {
private static Set<Class<?>> classes;
private static final Set<String> CONSIDERED_MODULES = Set.of("java.base");
public static void main(String[] args) {
try {
findClasses();
classes.forEach(System.out::println);
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void findClasses() throws IOException {
classes = new HashSet<>();
File root = new File(System.getProperty("java.home"));
File lib = new File(root, "lib");
ZipFile srczip = new ZipFile(new File(lib, "src.zip"));
Iterator<? extends ZipEntry> itr = srczip.entries().asIterator();
while(itr.hasNext())
extractFromEntry(itr.next());
}
private static void extractFromEntry(ZipEntry entry) {
String name = entry.getName();
if(name.endsWith(".java")) {
int firstSlash = name.indexOf('/');
String moduleName = name.substring(0, firstSlash);
if(!CONSIDERED_MODULES.contains(moduleName)) return;
String fullyQualifiedName = name.substring(firstSlash + 1, name.length() - 5).replace('/', '.');
if(fullyQualifiedName.endsWith("-info")) return; //catches module-info or package-info files
try {
Class<?> clazz = Class.forName(fullyQualifiedName);
classes.add(clazz);
}
catch (ClassNotFoundException e) {}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.