Java Code Examples for org.objectweb.asm.MethodVisitor#visitParameter()

The following examples show how to use org.objectweb.asm.MethodVisitor#visitParameter() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static byte[] createInterface() {
  ClassWriter cw = new ClassWriter(0);
  MethodVisitor mv;

  cw.visit(
      V1_8,
      ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE,
      INTERFACE_TYPE_NAME,
      null,
      "java/lang/Object",
      null);

  cw.visitInnerClass(
      INTERFACE_TYPE_NAME,
      CLASS_NAME,
      "Interface",
      ACC_PUBLIC | ACC_STATIC | ACC_ABSTRACT | ACC_INTERFACE);

  {
    mv =
        cw.visitMethod(
            ACC_PUBLIC | ACC_ABSTRACT,
            "call",
            "(Ljava/lang/String;)Ljava/lang/String;",
            null,
            null);
    mv.visitParameter("input", 0);
    mv.visitEnd();
  }
  cw.visitEnd();

  return cw.toByteArray();
}
 
Example 2
private void visitParameter(
    int index,
    VariableElement parameter,
    Name name,
    int access,
    List<? extends AnnotationMirror> annotationMirrors,
    MethodVisitor methodVisitor) {
  if (includeParameterMetadata) {
    methodVisitor.visitParameter(name.toString(), access);
  }

  for (AnnotationMirror annotationMirror : annotationMirrors) {
    try {
      if (MoreElements.isSourceRetention(annotationMirror)) {
        continue;
      }
    } catch (CannotInferException e) {
      reportMissingAnnotationType(parameter, annotationMirror);
      continue;
    }
    // Note: We purposely don't attempt to remap source level parameter indices to bytecode
    //       parameter indices here when we have a synthetic first parameter for an inner class
    //       constructor, as this would cause ASM to emit an empty parameter annotation entry
    //       for the synthetic parameter. See comment in <code>visitParameters</code>.
    visitAnnotationValues(
        annotationMirror,
        methodVisitor.visitParameterAnnotation(
            index,
            descriptorFactory.getDescriptor(annotationMirror.getAnnotationType()),
            MoreElements.isRuntimeRetention(annotationMirror)));
  }
}
 
Example 3
private void generateJvmBridge(MethodInfo method) {
    // get a bounds-erased descriptor
    String descriptor = AsmUtil.getDescriptor(method, name -> null);
    // make sure we need a bridge
    if (!userMethods.contains(method.name() + "/" + descriptor)) {
        MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE,
                method.name(),
                descriptor,
                null,
                null);
        List<org.jboss.jandex.Type> parameters = method.parameters();
        for (int i = 0; i < parameters.size(); i++) {
            mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
        }
        mv.visitCode();
        // this
        mv.visitIntInsn(Opcodes.ALOAD, 0);
        // each param
        for (int i = 0; i < parameters.size(); i++) {
            org.jboss.jandex.Type paramType = parameters.get(i);
            if (paramType.kind() == Kind.PRIMITIVE)
                throw new IllegalStateException("BUG: Don't know how to generate JVM bridge method for " + method
                        + ": has primitive parameters");
            mv.visitIntInsn(Opcodes.ALOAD, i + 1);
            if (paramType.kind() == Kind.TYPE_VARIABLE) {
                String typeParamName = paramType.asTypeVariable().identifier();
                switch (typeParamName) {
                    case "Entity":
                        mv.visitTypeInsn(Opcodes.CHECKCAST, entityBinaryType);
                        break;
                    case "Id":
                        mv.visitTypeInsn(Opcodes.CHECKCAST, idBinaryType);
                        break;
                }
            }
        }

        String targetDescriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                daoBinaryName,
                method.name(),
                targetDescriptor, false);
        String targetReturnTypeDescriptor = targetDescriptor.substring(targetDescriptor.indexOf(')') + 1);
        mv.visitInsn(AsmUtil.getReturnInstruction(targetReturnTypeDescriptor));
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

}
 
Example 4
private void generateModelBridge(MethodInfo method, AnnotationValue targetReturnTypeErased) {
    String descriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
    // JpaOperations erases the Id type to Object
    String descriptorForJpaOperations = AsmUtil.getDescriptor(method,
            name -> name.equals("Entity") ? entitySignature : null);
    String signature = AsmUtil.getSignature(method, name -> typeArguments.get(name));
    List<org.jboss.jandex.Type> parameters = method.parameters();

    String castTo = null;
    if (targetReturnTypeErased != null && targetReturnTypeErased.asBoolean()) {
        org.jboss.jandex.Type type = method.returnType();
        if (type.kind() == Kind.TYPE_VARIABLE &&
                type.asTypeVariable().identifier().equals("Entity")) {
            castTo = entityBinaryType;
        }
        if (castTo == null)
            castTo = type.name().toString('/');
    }

    // Note: we can't use SYNTHETIC here because otherwise Mockito will never mock these methods
    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC,
            method.name(),
            descriptor,
            signature,
            null);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
    }
    mv.visitCode();
    injectModel(mv);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitIntInsn(Opcodes.ALOAD, i + 1);
    }
    // inject Class
    String forwardingDescriptor = "(" + getModelDescriptor() + descriptorForJpaOperations.substring(1);
    if (castTo != null) {
        // return type is erased to Object
        int lastParen = forwardingDescriptor.lastIndexOf(')');
        forwardingDescriptor = forwardingDescriptor.substring(0, lastParen + 1) + "Ljava/lang/Object;";
    }
    mv.visitMethodInsn(Opcodes.INVOKESTATIC,
            getPanacheOperationsBinaryName(),
            method.name(),
            forwardingDescriptor, false);
    if (castTo != null)
        mv.visitTypeInsn(Opcodes.CHECKCAST, castTo);
    String returnTypeDescriptor = descriptor.substring(descriptor.lastIndexOf(")") + 1);
    mv.visitInsn(AsmUtil.getReturnInstruction(returnTypeDescriptor));
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 5
Source Project: quarkus   File: PanacheEntityEnhancer.java    License: Apache License 2.0 4 votes vote down vote up
private void generateMethod(MethodInfo method, AnnotationValue targetReturnTypeErased) {
    String descriptor = AsmUtil.getDescriptor(method, name -> null);
    String signature = AsmUtil.getSignature(method, name -> null);
    List<org.jboss.jandex.Type> parameters = method.parameters();
    String castTo = null;
    if (targetReturnTypeErased != null && targetReturnTypeErased.asBoolean()) {
        castTo = method.returnType().name().toString('/');
    }

    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC,
            method.name(),
            descriptor,
            signature,
            null);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
    }
    mv.visitCode();
    for (PanacheMethodCustomizer customizer : methodCustomizers) {
        customizer.customize(thisClass, method, mv);
    }
    // inject model
    injectModel(mv);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitIntInsn(Opcodes.ALOAD, i);
    }
    // inject Class
    String forwardingDescriptor = "(" + getModelDescriptor() + descriptor.substring(1);
    if (castTo != null) {
        // return type is erased to Object
        int lastParen = forwardingDescriptor.lastIndexOf(')');
        forwardingDescriptor = forwardingDescriptor.substring(0, lastParen + 1) + "Ljava/lang/Object;";
    }
    mv.visitMethodInsn(Opcodes.INVOKESTATIC,
            getPanacheOperationsBinaryName(),
            method.name(),
            forwardingDescriptor, false);
    if (castTo != null)
        mv.visitTypeInsn(Opcodes.CHECKCAST, castTo);
    String returnTypeDescriptor = descriptor.substring(descriptor.lastIndexOf(")") + 1);
    mv.visitInsn(AsmUtil.getReturnInstruction(returnTypeDescriptor));
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 6
Source Project: groovy   File: AsmClassGenerator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
    controller.resetLineNumber();
    Parameter[] parameters = node.getParameters();
    String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), parameters);
    String signature = BytecodeHelper.getGenericsMethodSignature(node);
    int modifiers = node.getModifiers();
    if (isVargs(node.getParameters())) modifiers |= ACC_VARARGS;
    MethodVisitor mv = classVisitor.visitMethod(modifiers, node.getName(), methodType, signature, buildExceptions(node.getExceptions()));
    controller.setMethodVisitor(mv);

    visitAnnotations(node, mv);
    for (int i = 0, n = parameters.length; i < n; i += 1) {
        visitParameterAnnotations(parameters[i], i, mv);
    }

    // add parameter names to the MethodVisitor (jdk8+ only)
    if (Optional.ofNullable(controller.getClassNode().getCompileUnit())
            .orElseGet(context::getCompileUnit).getConfig().getParameters()) {
        for (Parameter parameter : parameters) {
            // TODO: handle ACC_SYNTHETIC for enum method parameters?
            mv.visitParameter(parameter.getName(), 0);
        }
    }

    if (controller.getClassNode().isAnnotationDefinition() && !node.isStaticConstructor()) {
        visitAnnotationDefault(node, mv);
    } else if (!node.isAbstract()) {
        Statement code = node.getCode();
        mv.visitCode();

        BytecodeInstruction instruction; // fast path for getters, setters, etc.
        if (code instanceof BytecodeSequence && (instruction = ((BytecodeSequence) code).getBytecodeInstruction()) != null) {
           instruction.visit(mv);
        } else {
            visitStdMethod(node, isConstructor, parameters, code);
        }

        try {
            mv.visitMaxs(0, 0);
        } catch (Exception e) {
            Writer writer = null;
            if (mv instanceof TraceMethodVisitor) {
                TraceMethodVisitor tracer = (TraceMethodVisitor) mv;
                writer = new StringBuilderWriter();
                PrintWriter p = new PrintWriter(writer);
                tracer.p.print(p);
                p.flush();
            }
            StringBuilder message = new StringBuilder(64);
            message.append("ASM reporting processing error for ");
            message.append(controller.getClassNode().toString()).append("#").append(node.getName());
            message.append(" with signature ").append(node.getTypeDescriptor());
            message.append(" in ").append(sourceFile).append(":").append(node.getLineNumber());
            if (writer != null) {
                message.append("\nLast known generated bytecode in last generated method or constructor:\n");
                message.append(writer);
            }
            throw new GroovyRuntimeException(message.toString(), e);
        }
    }
    mv.visitEnd();
}
 
Example 7
/**
 * Makes the given visitor visit this parameter declaration.
 *
 * @param methodVisitor
 *          a method visitor.
 */
public void accept(final MethodVisitor methodVisitor) {
	methodVisitor.visitParameter(name, access);
}
 
Example 8
Source Project: Concurnas   File: ParameterNode.java    License: MIT License 2 votes vote down vote up
/**
 * Makes the given visitor visit this parameter declaration.
 *
 * @param methodVisitor a method visitor.
 */
public void accept(final MethodVisitor methodVisitor) {
  methodVisitor.visitParameter(name, access);
}
 
Example 9
/**
 * Makes the given visitor visit this parameter declaration.
 * 
 * @param mv
 *          a method visitor.
 */
public void accept(final MethodVisitor mv) {
  mv.visitParameter(name, access);
}
 
Example 10
Source Project: JReFrameworker   File: ParameterNode.java    License: MIT License 2 votes vote down vote up
/**
 * Makes the given visitor visit this parameter declaration.
 *
 * @param methodVisitor a method visitor.
 */
public void accept(final MethodVisitor methodVisitor) {
  methodVisitor.visitParameter(name, access);
}
 
Example 11
Source Project: JReFrameworker   File: ParameterNode.java    License: MIT License 2 votes vote down vote up
/**
 * Makes the given visitor visit this parameter declaration.
 *
 * @param methodVisitor a method visitor.
 */
public void accept(final MethodVisitor methodVisitor) {
  methodVisitor.visitParameter(name, access);
}