Reading a Java .class file
-
24-10-2019 - |
سؤال
I want to write a tool which generates some code using a compiled .class
file as input. Specifically, I want to read from this class file:
- Methods, with annotations
- Method parameters, with annotations
The input class file will likely refer to several types that are not in the tool's classpath. This is ok, I don't need to do anything with them, just need to read fully qualified type names as strings. I do need to get some information from the annotations, but they will be in the tool's classpath.
Is there a library which I can use for this purpose? It would be nice if the API was a bit like the reflection API, but it doesn't have to be.
المحلول
ASM http://asm.ow2.org/ allows you to read a class from a file/input stream without class loading it. It allows you to see annotations which are not loaded at runtime. It can also be used to modify the class byte code/annotations/method etc.
نصائح أخرى
The javap tool included with the JDK probably already does what you're after.
You need to look at two things Reflection API
and Decompiler
I think you could use spring class scanning.
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "org/springframework/samples/petclinic";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
System.out.printf("Component: %s\n", component.getBeanClassName());
}
for more information you can look into spring docs
I'm using asm for finding out all the methods.
If you have access to generating the .class file then the Reflection API should be able to help.