简体   繁体   中英

How to check bytecode length of java method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM