问题
I have an assignment where i need to write a Java program that parses a .class file and retrieves things like :
1.name of the .java file
2.implemented interfaces
3.variables
4.constructors
5.methods
I don't have any ideeas where to begin from? For example,what kind of Data I/O structure should I use?
回答1:
There are already several libraries for classfile parsing out there. Objectweb ASM is the most popular.
If you have to do it from scratch, that I'd recommend starting by the JVM specification, which explains the binary layout of classfiles in detail. After that, parsing is just a simple matter of programming. I've written a classfile parser before, it's not that hard.
回答2:
You don't need any external library, just use java.lang.Class
. Write the name of your class:
[NameOfMyClass].class.getDeclaredFields();
[NameOfMyClass].class.getDeclaredConstructors();
[NameOfMyClass].class.getDeclaredMethods();
It's the same for interfaces and many other attributes.
回答3:
You can use Java Reflection. Here is a good tutorial -->
Java Reflection Tutorial
回答4:
- You can you
ClassParser
which is available in Apache commons library. you can read the Javadoc here. You can download apache commons from here - You can also use Java reflection API which provides method such as
getDeclaredFileds
,getDeclaredMethods
etc.
来源:https://stackoverflow.com/questions/24697562/class-file-parser