我已经从这篇文章中了解了如何使用 ASM 在运行时操作类。
但我对如何修改常量池还有进一步的疑问。下面是我要修改的示例 java 程序
主jar文件:
public class test {
private static final String a = "Hello World";
private static final String b = "ASM is awasome";
public static void main(String[] args) {
int x = 10;
int y = 25;
int z = x * y;
System.out.println(a);
System.out.println(z);
System.out.println(b);
}
}
我想将变量a
从修改"Hello World"
为"Multiply Of x*y is: "
我的代理班
import java.lang.instrument.*;
import java.security.ProtectionDomain;
import org.objectweb.asm.*;
public class ExampleAgent implements ClassFileTransformer {
private static final String TRANSFORM_CLASS = "src/test";
private static final String TRANSFORM_METHOD_NAME = "main";
private static final String TRANSFORM_METHOD_DESC = "([Ljava/lang/String;)V";
public static void premain(String arg, Instrumentation instrumentation) {
instrumentation.addTransformer(new ExampleAgent());
}
public byte[] transform(ClassLoader loader, String className, Class<?> cl,
ProtectionDomain pd, byte[] classfileBuffer) {
if(!TRANSFORM_CLASS.equals(className)) return null;
ClassReader cr = new ClassReader(classfileBuffer);
ClassWriter cw = new ClassWriter(cr, 0);
cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {
@Override
public MethodVisitor visitMethod(int access, String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(
access, name, desc, signature, exceptions);
//Code to modify the value of a
return mv;
}
}, 0);
return cw.toByteArray();
}
}
控制台窗口上的结果应该是
Multiply Of x*y is:
250
ASM is awasome