要让ASM的visitMethod在访问Scala中的方法时起作用,需要使用Scala ASM库。示例代码如下:
import org.objectweb.asm.Opcodes import org.objectweb.asm.ClassWriter import org.objectweb.asm.MethodVisitor import scala.tools.asm.ScalaSigAttributeParsers import scala.tools.asm.ClassReader import org.objectweb.asm.ClassVisitor
/**
/**
/**
val methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "visitMe", "()V", null, null)
methodVisitor.visitCode()
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")
methodVisitor.visitLdcInsn("Visited method using ASM in Scala")
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false)
methodVisitor.visitInsn(Opcodes.RETURN)
methodVisitor.visitMaxs(0, 0)
methodVisitor.visitEnd()
val classReader = new ClassReader(classWriter.toByteArray())
val classVisitor = new ClassVisitor(Opcodes.ASM5) {
override def visitMethod(access: Int, name: String, descriptor: String, signature: String, exceptions: Array[String]): MethodVisitor = {
if (name == "visitMe") {
methodVisitor
} else {
super.visitMethod(access, name, descriptor, signature, exceptions)
}
}
}
classReader.accept(classVisitor, 0)
} }
val myClass = new MyClass() myClass.visitMethod() // call ASM to visit the method