返回顶部

收藏

java使用ASM字节码工具调用类方法和实例方法

更多

调用静态方法:

//int c=sample.InvokeMethod.add(2,3);
mv.visitInsn(ICONST_2); //arg1
mv.visitInsn(ICONST_3); //arg2

mv.visitMethodInsn(INVOKESTATIC, 
   "sample/InvokeMethod", //class name
   "add", //static method name
  "(II)I"); //return type is integer

调用实例方法:

//obj.cal(4,5);
mv.visitVarInsn(ALOAD, 2); //load object from stack
mv.visitInsn(ICONST_4); //arg1
mv.visitInsn(ICONST_5); //arg2
mv.visitMethodInsn(INVOKEVIRTUAL, "sample/InvokeMethod", "cal", "(II)V");

实例化对象,即调用构造函数:

//sample.InvokeMethod obj=new sample.InvokeMethod(6,7);
mv.visitTypeInsn(NEW, "sample/InvokeMethod");
mv.visitInsn(DUP);
mv.visitIntInsn(BIPUSH, 6);
mv.visitIntInsn(BIPUSH, 7);
mv.visitMethodInsn(INVOKESPECIAL, "sample/InvokeMethod", "<init>", "()V");
mv.visitVarInsn(ASTORE, 4);

标签:java,asm

收藏

0人收藏

支持

0

反对

0

发表评论