java - how to eliminate of primitive type and get unused of local variable

323 views Asked by At

i have an example simple code :

class Test {
    void method(boolean boo){
        String b;
        int a=0;
        try
        {
            java.awt.image.BufferedImage image=null;
            new Thread().sleep(1000);
            javax.swing.JOptionPane.showMessageDialog(null,"test");
            java.io.File file=new java.io.File("C:\\file.png");
            boolean boo=file.exists();
            if(boo==true)
                image=javax.imageio.ImageIO.read(file);
        }
        catch(InterruptedException e){}
    }
}

Basically i have to use BCEL to access the byte code and reach my objective. so, i have try create simple code :

import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;

class javap
{
    public static void main(String[]args)
    {
        try
        {
            JavaClass jc = Repository.lookupClass("Test");
            ConstantPool constantPool = jc.getConstantPool();
            Method [] method=jc.getMethods();
            for (Method m : method) 
            {
                LocalVariableTable lvt=m.getLocalVariableTable();
                LocalVariable[] lv=lvt.getLocalVariableTable();
                for(LocalVariable l : lv)
                {   
                    System.out.println(l.getName()+" : "+l.getSignature());
                }
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Result :

local variable : this --> LTest;
local variable : image --> Ljava/awt/image/BufferedImage;
local variable : file --> Ljava/io/File;
local variable : boo --> Z
local variable : ex --> Ljava/lang/Exception;
local variable : this --> LTest;
local variable : a --> I

How to eliminate primitive types that have been retrieved like a as int and boo as boolean, and how to retrieve unused local variable like String b ?

-Thanks-

1

There are 1 answers

4
Sharon Ben Asher On

Regarding retrieval of unused local variable: I ran your code and I see that the LocalVariableTable doesn't seem to contain the unsued String. When I "use" it by initializing it, the variable will be added to the table. I searched and according to this thread the JIT (or perhaps the compiler? since it is the one creating the bytecode) optimizes the code and removes the unsued var completely from the bytecode.