Can javassist modify a statement in a conditional expression?

I need to know if with the following code and with javassist I can manipulate the code to replace the logical operator ">" with "<".

Here is the class whose bytecode I want to manipulate:

public class TryClass {
    public void foo(){
        int a =0;
        if(a>5){
            System.out.println("I love apples");
       }
        else{
            System.out.println("I hate apples");
       }
    }
}

After the manipulation, the class execution should be printed: "I love apples" instead of: "I hate apples"

+4
source share
2 answers

< >, if_icmple, , , . javassist , , .  

+2

ExprEditor Expr, ( ):

  • catch

. , ExprEditor::loopBody:

       if (c < Opcode.GETSTATIC)   // c < 178
            /* skip */;

, if_icmple= 164, .

Javassist API- , API - javassist.bytecode. , bytecode .

- foo, (, javap):

   0: iconst_0
   1: istore_1
   2: iload_1
   3: iconst_5
   4: if_icmple     18
   7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  10: ldc           #3                  // String I love apples
  12: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  15: goto          26
  18: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  21: ldc           #5                  // String I hate apples
  23: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
  26: return

, a > 5 if_icmple (< =) compare and branch to else, , . , if_icmple if_icmpgt.

, , API- Javassist bytecode:

CtClass cc = ClassPool.getDefault().get("TryClass");
CtMethod fooMethod = cc.getDeclaredMethod("foo");

CodeIterator codeIterator = fooMethod.getMethodInfo().getCodeAttribute().iterator();
while (codeIterator.hasNext()) {
  int pos = codeIterator.next();
  int opcode = codeIterator.byteAt(pos);

  if(opcode == Opcode.IF_ICMPLE) {
    codeIterator.writeByte(Opcode.IF_ICMPGT, pos);
    break;
  }
}

TryClass test = (TryClass) cc.toClass().newInstance();
test.foo();

, , . , . , LocalVariableTable ( ) CodeAttribute , .

0

Source: https://habr.com/ru/post/1689104/


All Articles