final String signature, final String superName,
final String[] interfaces) {
String enhancedName = name + "$EnhancedByASM"; //改變類命名
enhancedSuperName = name; //改變父類,這里是”Account”
super.visit(version, access, enhancedName, signature,
enhancedSuperName, interfaces);
}
改進 visitMethod
方法,增加對構造函數的處理:
public MethodVisitor visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions) {
MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
MethodVisitor wrappedMv = mv;
if (mv != null) {
if (name.equals("operation")) {
wrappedMv = new AddSecurityCheckMethodAdapter(mv);
} else if (name.equals("<init>")) {
wrappedMv = new ChangeToChildConstructorMethodAdapter(mv,
enhancedSuperName);
}
}
return wrappedMv;
}
這里 ChangeToChildConstructorMethodAdapter
將負責把 Account
的構造函數改造成其子類 Account$EnhancedByASM
的構造函數
Account$EnhancedByASM 的構造函數:
class ChangeToChildConstructorMethodAdapter extends MethodAdapter { private String superClassName; public ChangeToChildConstructorMethodAdapter(MethodVisitor mv, String superClassName) { super(mv); this.superClassName = superClassName; } public void visitMethodInsn(int opcode, String owner, String name, String desc) { //調用父類的構造函數時 if (opcode == Opcodes.INVOKESPECIAL && name.equals("<init>")) { owner = superClassName; } super.visitMethodInsn(opcode, owner, name, desc);//改寫父類為superClassName } } |