Java
ClassReader
Write class reading with the ASM ClassReader.
Traversal with ClassReader
ClassReader is the class that walks the class structure and drives a ClassVisitor. Its accept(ClassVisitor v) method first calls visitClass, then visitMethod for each method. In ASM ClassReader parses real bytecode; we hold a name and a method list.
This model mirrors the ASM event flow: visit start, each method, visit end. The visitor catches these events and does what it wants.
Anonymous visitor
You do not have to open a new class file to implement an interface. With an anonymous class you define the visitor in place: new ClassVisitor() { ... }. This is practical for one-off implementations.
The anonymous class must implement all methods of the interface. By putting System.out.println inside visitClass and visitMethod you can print the events to the screen.
Exercise Write the ClassReader class and accept method
Add a void visitMethod(String name); method to the ClassVisitor interface above. Define class ClassReader with String name and String[] methods fields and a ClassReader(String name, String[] methods) constructor. A void accept(ClassVisitor v) method first calls v.visitClass(name), then v.visitMethod(m) for each method. In main create ClassReader reader = new ClassReader("Main", new String[]{"main"});, call reader.accept(...) with an anonymous ClassVisitor whose visitClass prints System.out.println("Class: " + n); and visitMethod prints System.out.println("Method: " + n);.
Show example solution
interface ClassVisitor {
void visitClass(String name);
void visitMethod(String name);
}
class ClassReader {
String name;
String[] methods;
ClassReader(String name, String[] methods) {
this.name = name;
this.methods = methods;
}
void accept(ClassVisitor v) {
v.visitClass(name);
for (String m : methods) v.visitMethod(m);
}
}
public class Main {
public static void main(String[] args) {
ClassReader reader = new ClassReader("Main", new String[]{"main"});
reader.accept(new ClassVisitor() {
public void visitClass(String n) { System.out.println("Class: " + n); }
public void visitMethod(String n) { System.out.println("Method: " + n); }
});
}
}
Test yourself
-
Complete the accept call
reader.____(visitor);
Show answer
reader.accept(visitor);
-
What does ClassReader.accept do?
- It compiles the class
- It deletes files
- It drives the visitor
- It starts threads
Show answer
It drives the visitor — accept drives the visitor with class and method events.
-
Match the ClassReader elements
- accept
- Drives the visitor
- name
- Class name
- methods
- Method list
- visitMethod
- For each method
Next lesson: ClassVisitor