Project design
- Java course
- Expert
- Lesson 37/46
- 6 min
Design the bytecode analysis project skeleton.
Project: bytecode inspector
In this five-lesson project you will build a bytecode inspector. Each lesson adds one piece, and by the final lesson you will complete a working mini inspector. You will model the visitor pattern from the ASM library with plain Java.
First you will define the ClassVisitor interface: a void visitClass(String name); method visits the class name. In later lessons you will traverse the class with ClassReader, produce output with ClassWriter, then transform and combine.
The class file format
A .class file has a fixed structure: the magic number 0xCAFEBABE, version, constant pool, access flags, this/super, fields, methods and attributes. ASM parses this structure.
In this project we model a visitor pattern with plain Java instead of ASM. A ClassReader class walks the method names as if reading a class file and calls the visitor. This is enough to understand how ASM works.
Practice Define the ClassVisitor interface
Define the ClassVisitor interface with a void visitClass(String name); method. In Main's main method print System.out.println("inspector ready");.
Starter code
// Define the ClassVisitor interface (visitClass method)
// Define the Main class and print inspector ready in mainSample solution
interface ClassVisitor {
void visitClass(String name);
}
public class Main {
public static void main(String[] args) {
System.out.println("inspector ready");
}
}Expected output
inspector ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does this project do?
- It manages a database
- It inspects class structure Correct answer
- It sets up a web server
- It draws a window
Explanation: The project traverses class structure with the visitor pattern.
2 Complete the visitor method
void ____(String name);
void visitClass(String name);
Explanation: visitClass is the method that visits the class name.
3 Match the class file sections
| Term | Meaning |
|---|---|
0xCAFEBABE |
Magic number |
constant pool |
Constant pool |
access flags |
Access flags |
methods |
Method table |