首页 > 代码库 > Java ASM 简单例子
Java ASM 简单例子
Test的代码比较简单
public class Test { /** * @param args */ public static void main(String[] args) { test01(); } static void test01() { System.out.println("Hello In Test01!"); } }
对Test.class进行处理,添加test03的生成及调用
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.objectweb.asm.ClassAdapter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodAdapter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class Test_08 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("D:\\Test.class"); ClassReader reader = new ClassReader(fis); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); reader.accept(new MyClassVisivator(cw), 0); writeToFile(cw.toByteArray(), "D:\\Test.class"); } static void writeToFile(byte[] bytes, String fileName) { try { (new File(fileName)).createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); fos.write(bytes); fos.flush(); } catch (Exception e) { }finally{ try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } static class MyClassVisivator extends ClassAdapter { ClassVisitor mCv; public MyClassVisivator(ClassVisitor cv) { super(cv); mCv = cv; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); if ("main".equals(name)) { MyMethodVisitor mmv = new MyMethodVisitor(mv); return mmv; } return mv; } @Override public void visitEnd() { MethodVisitor mv = mCv.visitMethod(Opcodes.ACC_STATIC, "test03", "()V", null, null); if (mv != null) { mv.visitCode(); mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("Hello In Test03!"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } } static class MyMethodVisitor extends MethodAdapter { MethodVisitor mMv; public MyMethodVisitor(MethodVisitor mv) { super(mv); mMv = mv; } @Override public void visitInsn(int opcode) { if (opcode == Opcodes.RETURN) { System.out.println("Debug"); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "Test", "test03", "()V"); } super.visitInsn(opcode); } @Override public void visitEnd() { super.visitEnd(); } } }
相关jar包
Java ASM 简单例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。