如何检查java方法的字节码长度 [英] How to check bytecode length of java method

查看:109
本文介绍了如何检查java方法的字节码长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我参加了一个大型遗留项目,其中包含许多巨大的类和生成的代码。
我希望找到字节码长度大于8000字节的所有方法(因为OOTB Java不会对其进行优化)。

At this moment I participate in big legacy project with many huge classes and generated code. I wish to find all methods that have bytecode length bigger than 8000 bytes (because OOTB java will not optimize it).

我发现了这样的手动方式:在Java中,字节码有多少字节具有特定的方法?
,但是我的目标是自动扫描许多文件。

I found manual way like this: How many bytes of bytecode has a particular method in Java? , however my goal is to scan many files automatically.

我尝试使用jboss-javassist,但是AFAIK获取字节码长度仅在类级别可用。

I tried to use jboss-javassist, but AFAIK getting bytecode length is available only on class level.

推荐答案

但是,确实可能从来没有内联过巨大的方法,但是我对8000的阈值有疑问。此评论提出了一个更小的限制,尽管它仍然取决于平台和配置。

Huge methods might indeed never get inlined, however, but I have my doubts regarding the threshold of 8000. This comment suggests a much smaller limit, though it is platform and configuration dependent anyway.

没错,获取字节码长度需要在较低级别上处理类,但是,您没有指定尝试执行此操作时遇到的实际障碍Javassist。

You are right that getting bytecode length needs to process classes on that low level, however, you didn’t specify what actual obstacle you encountered when trying to do that with Javassist. A simple program doing that with Javassist, would be

try(InputStream is=javax.swing.JComponent.class.getResourceAsStream("JComponent.class")) {
    ClassFile​ cf = new ClassFile(new DataInputStream(is));
    for(MethodInfo mi: cf.getMethods()) {
        CodeAttribute ca = mi.getCodeAttribute();
        if(ca == null) continue; // abstract or native
        int bLen = ca.getCode().length;
        if(bLen > 300)
            System.out.println(mi.getName()+" "+mi.getDescriptor()+", "+bLen+" bytes");
    }
}

这是使用最新版本的编写和测试的在API中使用泛型的Javassist。如果您使用的是其他版本/旧版本,则必须使用

This has been written and tested with a recent version of Javassist that uses Generics in the API. If you have a different/older version, you have to use

try(InputStream is=javax.swing.JComponent.class.getResourceAsStream("JComponent.class")) {
    ClassFile​ cf = new ClassFile(new DataInputStream(is));
    for(Object miO: cf.getMethods()) {
        MethodInfo mi = (MethodInfo)miO;
        CodeAttribute ca = mi.getCodeAttribute();
        if(ca == null) continue; // abstract or native
        int bLen = ca.getCode().length;
        if(bLen > 300)
            System.out.println(mi.getName()+" "+mi.getDescriptor()+", "+bLen+" bytes");
    }
}

这篇关于如何检查java方法的字节码长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆