不知道为什么要查看原始字节码。我会看个别说明。
public class Box {
public Object o;
public void mutate() {
o = new Object();
}
public static void main(String... args) throws IOException {
ClassReader cr = new ClassReader(Box.class.getName());
ASMifierClassVisitor acv = new ASMifierClassVisitor(new PrintWriter(System.out));
cr.accept(acv, 0);
}
}
印刷
... lots of code ...
{
mv = cw.visitMethod(ACC_PUBLIC, "mutate", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(11, l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitTypeInsn(NEW, "java/lang/Object");
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
mv.visitFieldInsn(PUTFIELD, "Box", "o", "Ljava/lang/Object;");
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLineNumber(12, l1);
mv.visitInsn(RETURN);
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLocalVariable("this", "LBox;", null, l0, l2, 0);
mv.visitMaxs(3, 1);
mv.visitEnd();
}
... more code ...
你可以看到方法访问者被调用
mv.visitFieldInsn(PUTFIELD, "Box", "o", "Ljava/lang/Object;");
这应该告诉你你想知道什么。
如果你有一个构造函数(我建议你这样做)
private Object o;
public Box(Object o) {
this.o = o;
}
您可能希望以不同的方式对待这种“突变”,因为它在构造函数中。