Jayanga
Jayanga

Reputation: 887

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 initialization.

How can I initialize a static field?

Upvotes: 1

Views: 1602

Answers (2)

Matt
Matt

Reputation: 2189

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
    }
  }
}

Upvotes: 4

Amir Afghani
Amir Afghani

Reputation: 38551

You should be able to just override visitField in ClassVisitor

Upvotes: 0

Related Questions