javabcel

Identify Local variable data types in Apache Byte Code engineering library (bcel)


I'm using Apache bcel library to read java class files. It allows to identify the local variable names for a given method from the org.apache.bcel.classfile.Method.getLineNumberTable() call.

But the details does not include the data type related details of the local variables. And also could not find any other way of getting the variable daat types as well. Little help would be appreciated


Solution

  • Actually there is a way. We can get the local variable signature by iterating method.getLocalVariableTable().getLocalVariableTable(). Once we have the signature, there is a Utility class called org.apache.bcel.classfile.Utility and there is a conversion method Utility.signatureToString(variableSignature).

    Javadoc of Utility class - https://commons.apache.org/proper/commonsbcel/apidocs/org/apache/bcel/classfile/Utility.html

    Posting the example code segment

    This is the example java file which the class file will be used for analyzing

    public class ExampleClassFile {
        public void testClass(int input){
            int intVal= 0;
            String stringVal= "randomText";
            boolean booleanVal= false;
            int []intArray = new int[2];
        }
    }
    

    This is the bcel code for analyzing the above .class file

    JavaClass javaClass = Repository.lookupClass("ExampleClassFile");
    for(Method method: javaClass.getMethods()){
        for(LocalVariable localVariable: method.getLocalVariableTable().getLocalVariableTable()){
            System.out.println(Utility.signatureToString(localVariable.getSignature()) + " " + localVariable.getName());
        }
    }
    

    These are the output results

    1. int input
    2. int intVal
    3. String stringVal
    4. boolean booleanVal
    5. int[] intArray