-2

How to find the op-code for identifying switch case in a java class using javassist or asm.

I used the Below Snippet

List methods = lClassFile.getMethods();
        for (Object m : methods) {
            MethodInfo lMethodInfo = (MethodInfo) m;
            System.out.println("method name: " + lMethodInfo.getName());
            CodeAttribute ca = lMethodInfo.getCodeAttribute();
            for (CodeIterator ci = ca.iterator(); ci.hasNext();) {
                int index = ci.next();
                int op = ci.byteAt(index);

                if (op == Opcode.TABLESWITCH) {
                    int a1 = ci.s16bitAt(index + 1);
                    String fieldrefType = " " + lClassFile.getConstPool().getFieldrefType(a1);
                    String fieldName = " " + lClassFile.getConstPool().getFieldrefName(a1);
                    String fieldrefClassName = " " + lClassFile.getConstPool().getFieldrefClassName(a1);
                    System.out.println("1 -> FieldrefType = " + fieldrefType + "    field name: " + fieldName + "          FieldrefClassName name: " + fieldrefClassName);
                }
                if (op == Opcode.LOOKUPSWITCH) {
                    int a1 = ci.s16bitAt(index + 1);
                    String fieldrefType = " " + lClassFile.getConstPool().getFieldrefType(a1);
                    String fieldName = " " + lClassFile.getConstPool().getFieldrefName(a1);
                    String fieldrefClassName = " " + lClassFile.getConstPool().getFieldrefClassName(a1);
                    System.out.println("2 -> FieldrefType = " + fieldrefType + "    field name: " + fieldName + "          FieldrefClassName name: " + fieldrefClassName);
                }
            }
        }

I got Output as:

method name: <init>
method name: execute
2 -> FieldrefType =  null    field name:  null          FieldrefClassName name:  null
1 -> FieldrefType =  null    field name:  null          FieldrefClassName name:  null
method name: validate
2 -> FieldrefType =  null    field name:  null          FieldrefClassName name:  null
2 -> FieldrefType =  null    field name:  null          FieldrefClassName name:  null
method name: postExecute
2 -> FieldrefType =  null    field name:  null          FieldrefClassName name:  null
2 -> FieldrefType =  null    field name:  null          FieldrefClassName name:  null

Cant able to get the switch cases values. Help me please....

1 Answers1

1
  1. Write a class with a method that only contains a very simple switch/case statement
  2. Compile that class
  3. Look at the bytecode using javap -c MyClass

The bytecode contains TABLESWITCH or LOOKUPSWITCH and javassists Opcode class has corresponding static fields.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268