How to access and read JVMs class file members?
I'm not very familiar with JVM and I have an assignment in开发者_JS百科volving the Class file.
Write a java program that when run as
java DissectClassFile file1.class file2.class ...
it will print a summary of each class file as follows: the name of the class defined by the class file, its super class and interfaces it implements, the number of items in the constant pool, the number of interfaces implemented by the class, and their names, the number of fields of the class whose name contain the underscore character, the number of methods of the class whose names contain at least one capital letter
Right off the bat I don't know where to begin. If someone could help me out and point me in the correct direction, I should get the hang of it.
You need to read the Java Virtual Machine Specification. It contains an explanation of the class file format.
There is a class java.lang.Class to access that information. For every Class, you can call MyClass.class (for example, String.class) to get the object with the information for that class.
Most of this information can easily be gleaned loading each class using Class.forName(...)
and using the reflection APIs to fish out the information. However the constant pool size is the killer. AFAIK, this can only be determined from the class file itself.
So, your options would seem to be:
- Write a bunch of code to read and decode class files. The JVM spec has the details of the class file format.
- Use an existing library such as BCEL to take care of the low-level class file parsing.
- Use a hybrid of class file parsing (using either of the above) to extract the constant pool size, and the reflection APIs for the rest.
I imagine that your assignment hints at which way they expect you to go. But if not, I'd look at the BCEL approach first.
精彩评论