예제 #1
0
  /** 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();
  }
예제 #2
0
 public Assembler storeLocal(Type type, int index) {
   mv.visitVarInsn(type.getOpcode(ISTORE), index);
   return this;
 }
예제 #3
0
 public Assembler loadLocal(Type type, int index) {
   mv.visitVarInsn(type.getOpcode(ILOAD), index);
   return this;
 }