0

我有一个简单的示例代码:

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

基本上我必须使用 BCEL 来访问字节码并达到我的目标。所以,我尝试创建简单的代码:

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

结果 :

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

如何消除像aasintbooas这样检索到的原始类型boolean,以及如何检索未使用的局部变量 like String b

-谢谢-

4

1 回答 1

1

关于检索未使用的局部变量:我运行了您的代码,我看到LocalVariableTable似乎不包含未使用的字符串。当我通过初始化它来“使用”它时,该变量将被添加到表中。我搜索并根据这个线程JIT(或者可能是编译器?因为它是创建字节码的那个)优化代码并从字节码中完全删除未使用的 var。

于 2015-06-25T07:25:49.710 回答