8
I'm using the asm library to perform some Java bytecode modification - specifically to modify my classes to implement a new interface and associated methods. My current approach is using the core asm API via a javaagent. I'd like to keep this dynamic approach as opposed to statically modifying .class files.
At a higher level, my problem is that if I choose to modify class A, which extends from B, I also need to modify B. (Given my understanding of how classes are loaded in the JVM, I believe that class B will always be handed to a transformer before class A. (Please correct me if I'm wrong). Given that assumption, I'm thinking that I then need to go back and retransform B. My approach is captured in this bit of code:
public byte[] transform(ClassLoader l, String name, Class<?> clazz, ProtectionDomain d, byte[] b) {
throws IllegalClassFormatException {
// **1**
System.out.println("--->>> " + name);
if (interestingClass(name)) {
try {
ClassReader cr = new ClassReader(b);
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
PyClassVisitorAdapter pv = new PyClassVisitorAdapter(cw, name);
cr.accept(pv, 0);
// **2** Retrieve the superclass and try to transform that
if (! "Ljava/lang/Object;".equals(pv.getSuperName())) {
String cName = classJvmToCanonical(pv.getSuperName());
Class[] classes = inst.getAllLoadedClasses();
for (Class c : classes) {
if (c.getName().equals(cName)) {
inst.retransformClasses(c);
break;
}
}
}
// Dump the transformed class
ClassReader cr2 = new ClassReader(cw.toByteArray());
ClassWriter cw2 = new ClassWriter(cr2, 0);
TraceClassVisitor tcv = new TraceCl