Example #1
0
 // print the object on the top of the stack
 public Assembler printObject() {
   mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
   mv.visitInsn(SWAP);
   mv.visitMethodInsn(
       INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/Object;)V", false);
   return this;
 }
  /** Generate class bytes for java.lang.Runnable implementation and return the same. */
  public byte[] generate(Method method, String className) {
    int modifiers = method.getModifiers();
    // make sure that the method is public static
    // and accepts no arguments
    if (!Modifier.isStatic(modifiers)
        || !Modifier.isPublic(modifiers)
        || method.getParameterTypes().length != 0) {
      throw new IllegalArgumentException();
    }
    Class clazz = method.getDeclaringClass();
    modifiers = clazz.getModifiers();
    // make sure that the class is public as well
    if (!Modifier.isPublic(modifiers)) {
      throw new IllegalArgumentException();
    }

    ClassWriter cw = InstrumentUtils.newClassWriter();
    cw.visit(
        V1_1, ACC_PUBLIC, className, null, "java/lang/Object", new String[] {"java/lang/Runnable"});
    // creates a MethodWriter for the (implicit) constructor
    MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    // pushes the 'this' variable
    mw.visitVarInsn(ALOAD, 0);
    // invokes the super class constructor
    mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    mw.visitInsn(RETURN);
    mw.visitMaxs(1, 1);
    mw.visitEnd();

    // creates a MethodWriter for the 'main' method
    mw = cw.visitMethod(ACC_PUBLIC, "run", "()V", null, null);
    // invokes the given method
    mw.visitMethodInsn(
        INVOKESTATIC,
        Type.getInternalName(method.getDeclaringClass()),
        method.getName(),
        Type.getMethodDescriptor(method));
    mw.visitInsn(RETURN);
    mw.visitMaxs(1, 1);
    mw.visitEnd();
    return cw.toByteArray();
  }
Example #3
0
 public Assembler invokeInterface(String owner, String method, String desc) {
   mv.visitMethodInsn(INVOKEVIRTUAL, owner, method, desc, true);
   return this;
 }
Example #4
0
 public Assembler invokeStatic(String owner, String method, String desc) {
   mv.visitMethodInsn(INVOKESTATIC, owner, method, desc, false);
   return this;
 }
Example #5
0
 public Assembler invokeSpecial(String owner, String method, String desc) {
   mv.visitMethodInsn(INVOKESPECIAL, owner, method, desc, false);
   return this;
 }
Example #6
0
 public Assembler invokeVirtual(String owner, String method, String desc) {
   mv.visitMethodInsn(INVOKEVIRTUAL, owner, method, desc, false);
   return this;
 }