以下代码需要asm-5.0.2.jar和asm-commons-5.0.2.jar两个包。
class="java" name="code">
package com.shihuan.field;
public class AccountField {
String sql = "select * from tables";
public void operation() {
System.out.println("shihuan operation...");
}
int executeInternal() {
System.out.println("shihuan executeInternal...");
return 1;
}
}
package com.shihuan.field;
public class TestAccountField {
public static void main(String[] args) {
AccountField t = new AccountField();
t.operation();
t.executeInternal();
}
}
package com.shihuan.field;
public class SecurityCheckerField {
public static java.util.Date getStartTime() {
long starttime = System.currentTimeMillis();
java.util.Date startdate = new java.util.Date(starttime);
System.out.println("shihuan starttime --->> " + startdate);
return startdate;
}
public static void checkCode(AccountField afObj) {
long endtime = System.currentTimeMillis();
java.util.Date enddate = new java.util.Date(endtime);
System.out.println("shihuan endtime --->> " + enddate);
System.out.println(afObj.sql);
}
}
package com.shihuan.field;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class GeneratorAsmField {
public static void main(String[] args) throws IOException {
ClassReader cr = new ClassReader("com.shihuan.field.AccountField");
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); // 先得到原始的方法
MethodVisitor newMethod = mv;
if (mv != null) {
if ("executeInternal".equals(name)) { // 此处的executeInternal即为需要修改的方法,修改方法內容
// 访问需要修改的方法
newMethod = new MethodVisitor(Opcodes.ASM5, mv) {
public void visitCode() {
visitMethodInsn(
Opcodes.INVOKESTATIC,
"com/shihuan/field/SecurityCheckerField",
"getStartTime", "()Ljava/util/Date;", false);
super.visitCode();
}
public void visitInsn(int opcode) {
if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {
visitVarInsn(Opcodes.ALOAD, 0);
visitMethodInsn(Opcodes.INVOKESTATIC, "com/shihuan/field/SecurityCheckerField", "checkCode", "(Lcom/shihuan/field/AccountField;)V", false);
}
super.visitInsn(opcode);
}
};
}
}
return newMethod;
}
};
cr.accept(cv, ClassReader.SKIP_DEBUG);
byte[] code = cw.toByteArray();
OutputStream fos = new FileOutputStream("D:/myworkspace/JavaAsm/bin/com/shihuan/field/AccountField.class");
fos.write(code);
fos.close();
}
}
网友 2014/6/3 20:33:45 发表
转载请注明出处,谢谢!