You are viewing a plain text version of this content. The canonical link for it is here.
Posted to bcel-user@jakarta.apache.org by Yuklai Suen <sa...@mail.utexas.edu> on 2004/10/08 07:10:17 UTC

Question on LocalVariableTable

Hi, 
I am trying to enumerate the local variables in the main function of HelloWorld.class. HelloWorld.java is attacted below:

public class HelloWorld {
    Object a = new Object();
    public static void main(String[] args) {
        int i = 1;
        Object obj = new Object();
        if (obj != null)
        {
            System.out.println("Hello World!");
        }
    }
}

I implemented 2 methods in a test class: 
    public void test1() {
        JavaClass clazz;
        try {
            clazz = Repository.lookupClass("HelloWorld");
        } 
        catch (Exception e) {
            System.out.println("No Class!");
            return;
        }
        Method[] m = clazz.getMethods();
        for (int i = 0; i < m.length; i++)
        {
            byte[] code = m[i].getCode().getCode();
            LocalVariableTable lvt = m[i].getLocalVariableTable();
            System.out.println(lvt);
        }
    }   
    
//I got this from a previous post from another user, thanks!
    public void test2() {
        JavaClass jClass;
        try {
            jClass = new ClassParser("HelloWorld.class").parse();
        }
        catch (Exception e)
        { 
            System.out.println(e);
            return;
        }
        ConstantPool cp = jClass.getConstantPool();
        ConstantPoolGen cpg = new ConstantPoolGen(cp);
        String className = jClass.getClassName();
        Method methods[] = jClass.getMethods();
        for (int i = 0; i < methods.length; i++) {
            MethodGen mg = new MethodGen(methods[i], className, cpg);
            LocalVariableGen vGen[] = mg.getLocalVariables();
            for (int k = 0; k < vGen.length; k++) {
                System.out.println(vGen[k].getName());
            }
        }
    }

test1() prints out "null" for the LocalVariableTable instance lvt; test2() prints out "this" and "arg0".

I have a couple of questions related to the result:
1. Why does lvt in test() get no local variable table? 
2. In the main method, I have actually 3 local variables as I believe. One is "this", one is "obj", and one is "i". Why does the test only print out 2 variables? Also, which local variable does "arg0" map to?

Thanks for the help to a beginner!