使用ASM注入字节码时出现StringIndexOutOfBoundsException错误

时间:2018-01-24 13:30:30

标签: java bytecode

早上好,
我正在尝试注入此代码:

int i = getKey();
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
System.out.println(timeStamp + " " + i);

使用 ASM库的现有方法内部。

所以我尝试在工具内部的一个非常基础的类中运行此代码:ASMifier。之后,我复制了我感兴趣的输出部分。

mv.visitTypeInsn(NEW, "java/text/SimpleDateFormat");
mv.visitInsn(DUP);
mv.visitLdcInsn("yyyy.MM.dd.HH.mm.ss");
mv.visitMethodInsn(INVOKESPECIAL, "java/text/SimpleDateFormat", "", "(Ljava/lang/String;)V", false);
mv.visitTypeInsn(NEW, "java/util/Date");
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, "java/util/Date", "", "()V", false);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/text/SimpleDateFormat", "format", "(Ljava/util/Date;)Ljava/lang/String;", false);
mv.visitVarInsn(ASTORE, 3);
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "", "()V", false);
mv.visitVarInsn(ALOAD, 3);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
mv.visitLdcInsn(" ");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
mv.visitVarInsn(ILOAD, 2);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);

但后来我收到了错误

*Exception in thread "main" 
java.lang.StringIndexOutOfBoundsException: String index out of range: 0

在编译时就行:

mv.visitMethodInsn(INVOKESPECIAL, "java/text/SimpleDateFormat", "", "(Ljava/lang/String;)V", false);

为什么我收到此错误?

栈跟踪:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at org.objectweb.asm.Frame.a(Unknown Source)
    at org.objectweb.asm.MethodWriter.visitMethodInsn(Unknown Source)
    at MethodAdapter.visitMethodInsn(MethodAdapter.java:33)
    at org.objectweb.asm.ClassReader.a(Unknown Source)
    at org.objectweb.asm.ClassReader.b(Unknown Source)
    at org.objectweb.asm.ClassReader.accept(Unknown Source)
    at org.objectweb.asm.ClassReader.accept(Unknown Source)
    at Main.main(Main.java:20)

1 个答案:

答案 0 :(得分:3)

看起来该方法的名称为空。

如果您尝试调用构造函数,请将方法名称设置为"<init>"