Search code examples
javacode-generationbytecode

Pushing to stack reference to the class begin generated with ASM


I'm using ASM Java library to generate a class X from scratch. Inside one of the static methods of this class I need to push a reference to X.class. Since there isn't yet a X.class I can't use visitLdcInsn. Is there a way to do it?

Well, it's possible (and I'm currently using it) to generate the following code (new X().getClass()), but I'm sure that's not the cleanest way to do it.


Solution

  • With generated code you usually don't need to push the class onto the stack. Anything you can do with a method call is usually available in byte code.

    Say you have to call a method with a class, you can push it onto the stack whether it exists or not.

    Something I use is the ASMifier. This is useful because you can start with a class which compiles and does what you want as a template and get it to dump all the code needed to recreate the class. This means you don't really need to write most of the code yourself.

    public class Main {
      public static void main(String... args) throws IOException {
        ASMifierClassVisitor cv = new ASMifierClassVisitor(new PrintWriter(System.out));
        ClassReader cr = new ClassReader("X");
        cr.accept(cv, 0);
      }
    }
    
    class X {
      {
        System.out.println("Inside class "+X.class);
      }
    }
    

    prints

    // lots of code
    mv.visitLdcInsn(Type.getType("LX;"));
    // more code.