下面列出了怎么用org.objectweb.asm.commons.InstructionAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public int writeCLInit(InstructionAdapter insts, String className) {
insts.iconst(values.size());
insts.newarray(Type.INT_TYPE);
int curIndex = 0;
for (Integer value : values) {
insts.dup();
insts.iconst(curIndex);
insts.iconst(value);
insts.astore(Type.INT_TYPE);
++curIndex;
}
insts.putstatic(className, fieldName, DESC);
// Needs up to 4 stack slots for: the array ref for the putstatic, the dup of the array ref
// for the store, the index, and the value to store.
return 4;
}
private static void writeStaticClassInit(
ClassWriter classWriter,
String className,
Collection<FieldInitializer> deferredInitializers) {
MethodVisitor visitor =
classWriter.visitMethod(
Opcodes.ACC_STATIC, "<clinit>", "()V", null, /* signature */ null /* exceptions */);
visitor.visitCode();
int stackSlotsNeeded = 0;
InstructionAdapter insts = new InstructionAdapter(visitor);
for (FieldInitializer fieldInit : deferredInitializers) {
stackSlotsNeeded = Math.max(stackSlotsNeeded, fieldInit.writeCLInit(insts, className));
}
insts.areturn(Type.VOID_TYPE);
visitor.visitMaxs(stackSlotsNeeded, 0);
visitor.visitEnd();
}
@Override
public int writeCLInit(InstructionAdapter insts, String className) {
insts.iconst(value);
insts.putstatic(className, fieldName, DESC);
// Just needs one stack slot for the iconst.
return 1;
}
/**
* Write the bytecode for the clinit portion of initializer.
*
* @return the number of stack slots needed for the code.
*/
int writeCLInit(InstructionAdapter insts, String className);