Search code examples
javajavassistbytecode-manipulation

Javassist : Bytecode.get() is not working


import javassist.bytecode.Bytecode;
import javassist.bytecode.ConstPool;
public class Coverage {

    public static void main(String[] args) {

        ConstPool cp = new ConstPool("Hello");
        byte[] b = new byte[100];
        Bytecode bc = new Bytecode(cp);
        b = bc.get();
        System.out.println("Bytecode start");
            for(int i = 0 ; i < b.length ; i++)
             {
                System.out.println(b);
             }
        System.out.println("Bytecode end");
    }

}            

bc.get() is not returning anything. My aim is to get the byte code of a class.


Solution

  • Well your System.out.println(b); is printing the whole array every time, you need System.out.println(b[i]); but I don't think that will work anyway. Try...

    public static void main(String[] args)  {
    
        ClassPool pool = ClassPool.getDefault();
    
        try {
            CtClass cc = pool.get("java.lang.String");
            byte[] bytes = cc.toBytecode();
    
            System.out.println("Bytecode start");
            for (Byte b : bytes) {
                System.out.println(b);
            }
            System.out.println("Bytecode end");
    
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (CannotCompileException e) {
            e.printStackTrace();
        }
    
    }