-2

如何使用 javassist 或 asm 在 java 类中找到用于识别 switch case 的操作码。

我使用了下面的片段

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);
                }
            }
        }

我得到的输出为:

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

无法获得开关案例值。请帮帮我....

4

1 回答 1

1
  1. 使用仅包含非常简单的 switch/case 语句的方法编写一个类
  2. 编译那个类
  3. 查看字节码使用javap -c MyClass

字节码包含TABLESWITCHorLOOKUPSWITCH并且 javassistsOpcode类具有相应的静态字段。

于 2013-02-04T05:25:02.420 回答