java 方法 字节码,如何检查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).

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.

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

解决方案

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.

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");

}

}

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");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值