开发者

Static Initializer in asm

I want to initialize a static field which I added to a class using asm. If I could access the static initializer then I could to the initializat开发者_如何学编程ion.

How can I initialize a static field?


I assume that you are adding the field by using a ClassAdapter that delegates almost everything to a ClassWriter but also calls visitField to add the new fields.

If the fields that you are adding are initialized to constants. Then you can simply supply an Object literal directly to ClassVisitor.visitField.

If the fields that you are adding require complicated static initialization, then you need to override ClassAdapter.visitMethod check for the <clinit> method and create a custom MethodAdapter that adds your desired code. A rough sketch of the code is as follows:

class MyAdapter extends ClassAdapter {
  public MyAdapter(ClassVisitor delegate) {
    super(delegate);
  }

  @Override
  public MethodVisitor visitMethod(int access, String name, 
                            String desc, String signature, String[] exceptions) {
    MethodVisitor r = super.visitMethod(access, name, desc, signature, exceptions);
    if ("<clinit>".equals(name)) {
      r = new MyMethodAdapter(r);
    }
    return r;
  }

  class MyMethodAdapter extends MethodAdapter {
    MyMethodAdapter(MethodVisitor delegate) {
      super(delegate);
    }

    @Override
    public void visitCode() {
      super.visitCode();
      // build my static initializer by calling
      // visitFieldInsn(int opcode, String owner, String name, String desc) 
      // or the like
    }
  }
}


You should be able to just override visitField in ClassVisitor

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜