Java Code Examples for java.lang.reflect.Method#getParameterAnnotations()

The following examples show how to use java.lang.reflect.Method#getParameterAnnotations() . 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
Source Project: arthas   File: BindingParserUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static List<Binding> parseBindings(Method method) {
    // 从 parameter 里解析出来 binding
    List<Binding> bindings = new ArrayList<Binding>();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    for (int parameterIndex = 0; parameterIndex < parameterAnnotations.length; ++parameterIndex) {
        Annotation[] annotationsOnParameter = parameterAnnotations[parameterIndex];
        for (int j = 0; j < annotationsOnParameter.length; ++j) {

            Annotation[] annotationsOnBinding = annotationsOnParameter[j].annotationType().getAnnotations();
            for (Annotation annotationOnBinding : annotationsOnBinding) {
                if (BindingParserHandler.class.isAssignableFrom(annotationOnBinding.annotationType())) {
                    BindingParserHandler bindingParserHandler = (BindingParserHandler) annotationOnBinding;
                    BindingParser bindingParser = InstanceUtils.newInstance(bindingParserHandler.parser());
                    Binding binding = bindingParser.parse(annotationsOnParameter[j]);
                    bindings.add(binding);
                }
            }
        }
    }
    return bindings;
}
 
Example 2
public static List<AggregateNativeContainerType> parseSignatureArgumentsTypes(Method inputFunction)
{
    ImmutableList.Builder<AggregateNativeContainerType> builder = ImmutableList.builder();

    for (int i = 0; i < inputFunction.getParameterCount(); i++) {
        Class<?> parameterType = inputFunction.getParameterTypes()[i];
        Annotation[] annotations = inputFunction.getParameterAnnotations()[i];

        // Skip injected parameters
        if (parameterType == ConnectorSession.class) {
            continue;
        }

        if (containsAnnotation(annotations, Parser::isAggregationMetaAnnotation)) {
            continue;
        }

        builder.add(new AggregateNativeContainerType(inputFunction.getParameterTypes()[i], isParameterBlock(annotations)));
    }

    return builder.build();
}
 
Example 3
public Annotation[][] getParameterAnnotations(final Method m) {
    Merger<Annotation[][]> merger = new Merger<Annotation[][]>(reader(m.getDeclaringClass())) {
        Annotation[][] reflection() {
            return ExternalMetadataReader.super.getParameterAnnotations(m);
        }

        Annotation[][] external() {
            JavaMethod jm = getJavaMethod(m, reader);
            Annotation[][] a = m.getParameterAnnotations();
            for (int i = 0; i < m.getParameterTypes().length; i++) {
                if (jm == null) continue;
                JavaParam jp = jm.getJavaParams().getJavaParam().get(i);
                a[i] = getAnnotations(jp.getParamAnnotation());
            }
            return a;
        }
    };
    return merger.merge();
}
 
Example 4
public Annotation[][] getParameterAnnotations(final Method m) {
    Merger<Annotation[][]> merger = new Merger<Annotation[][]>(reader(m.getDeclaringClass())) {
        Annotation[][] reflection() {
            return ExternalMetadataReader.super.getParameterAnnotations(m);
        }

        Annotation[][] external() {
            JavaMethod jm = getJavaMethod(m, reader);
            Annotation[][] a = m.getParameterAnnotations();
            for (int i = 0; i < m.getParameterTypes().length; i++) {
                if (jm == null) continue;
                JavaParam jp = jm.getJavaParams().getJavaParam().get(i);
                a[i] = getAnnotations(jp.getParamAnnotation());
            }
            return a;
        }
    };
    return merger.merge();
}
 
Example 5
public ChainLockableStrategy(Method method) {
    this.configurations = new Int2BooleanOpenHashMap();
    Annotation[][] annotations = method.getParameterAnnotations();
    for (int index = 0; index < annotations.length; index++) {
        for (Annotation annotation : annotations[index]) {
            if (annotation instanceof LockableParameter) {
                this.configurations.put(index, true);
                break;
            }
            if (annotation instanceof LockableElement) {
                // TODO 是否要检查参数的类型为数组/集合/映射
                this.configurations.put(index, false);
                break;
            }
        }
    }
}
 
Example 6
public boolean hasStartNanosAnnotation(Method method, int parameterIndex) {
    Annotation[][] parametersAnnotations = method.getParameterAnnotations();
    Annotation[] parameterAnnotations = parametersAnnotations[parameterIndex];
    for (Annotation annotation : parameterAnnotations) {
        if ((annotation instanceof StartNanos)) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source Project: Quicksql   File: ReflectUtil.java    License: MIT License 5 votes vote down vote up
/** Derives the name of the {@code i}th parameter of a method. */
public static String getParameterName(Method method, int i) {
  for (Annotation annotation : method.getParameterAnnotations()[i]) {
    if (annotation.annotationType() == Parameter.class) {
      return ((Parameter) annotation).name();
    }
  }
  return method.getParameters()[i].getName();
}
 
Example 8
void test1() throws Throwable {
    for (Method m : thisClass.getMethods()) {
        if (m.getName().equals("nop")) {
            Annotation[][] ann = m.getParameterAnnotations();
            equal(ann.length, 2);
            Annotation foo = ann[0][0];
            Annotation bar = ann[1][0];
            equal(foo.toString(), "@Named(value=foo)");
            equal(bar.toString(), "@Named(value=bar)");
            check(foo.equals(foo));
            check(! foo.equals(bar));
        }
    }
}
 
Example 9
Source Project: cxf   File: CodeGenTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderFromAnotherMessage3() throws Exception {
    env.put(ToolConstants.CFG_WSDLURL, getLocation("/wsdl2java_wsdl/pizza.wsdl"));
    env.put(ToolConstants.CFG_EXTRA_SOAPHEADER, "FALSE");
    env.remove(ToolConstants.CFG_VALIDATE_WSDL);
    processor.setContext(env);
    processor.execute();

    assertNotNull(output);

    Class<?> clz = classLoader.loadClass("com.mypizzaco.pizza.PizzaPortType");

    Method[] meths = clz.getMethods();
    for (Method m : meths) {
        if ("orderPizzaBroken".equals(m.getName())) {
            Annotation[][] annotations = m.getParameterAnnotations();
            assertEquals(1, annotations.length);
            for (int i = 0; i < 1; i++) {
                assertTrue(annotations[i][0] instanceof WebParam);
                WebParam parm = (WebParam)annotations[i][0];
                if ("OrderPizza".equals(parm.name())) {
                    assertEquals("http://mypizzaco.com/pizza/types", parm.targetNamespace());
                    assertEquals("OrderPizza", parm.name());
                    assertFalse(parm.header());
                } else if ("CallerIDHeader".equals(parm.name())) {
                    fail("If the exsh turned off, should not generate this parameter");
                } else {
                    fail("No WebParam found!");
                }
            }
        }
    }
}
 
Example 10
Source Project: Mockery   File: OptionalMockeryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void When_Call_Legal_Or_Illegal_With_Custom_Object_Return_Null()
    throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("checkCustomObject", Model.class);

  Optional annotation = (Optional) method.getParameterAnnotations()[0][0];
  Type type = method.getGenericParameterTypes()[0];
  Metadata<Optional> metadata = new Metadata<>(Providers.class,
      method, null, annotation, type);
  assertNull(optionalMockery.illegal(metadata));
  assertNull(optionalMockery.legal(metadata));
}
 
Example 11
Source Project: framework   File: CacheAdvice.java    License: Apache License 2.0 5 votes vote down vote up
private String getCacheKey(final String template, final Method method, final Object[] args)
    throws FrameworkException {
    if (StringUtils.isEmpty(template) && CommonUtil.isEmpty(args)) {
        throw new ServiceException(ErrorCodeDef.CACHE_ERROR_10002);
    }
    String key;
    if (StringUtils.isNotEmpty(template)) {
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        for (int i = 0; i < parameterAnnotations.length; i++) {
            for (Annotation annotation : parameterAnnotations[i]) {
                if (annotation instanceof Key) {
                    paramMap.put(((Key) annotation).value(), args[i]);
                    break;
                }
            }
        }
        key = VelocityParseFactory.parse(CommonUtil.getTransactionID(), template, paramMap);
        Assert.isFalse(key.contains(GlobalConstants.DOLLAR_BRACE), ErrorCodeDef.CACHE_ERROR_10002);
    }
    else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            if (i > 0) {
                sb.append(GlobalConstants.UNDERLINE);
            }
            sb.append(args[i] == null ? GlobalConstants.BLANK : args[i]);
        }
        key = sb.toString();
    }
    return key;
}
 
Example 12
Source Project: cxf   File: ResourceUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Parameter> getParameters(Method resourceMethod) {
    Annotation[][] paramAnns = resourceMethod.getParameterAnnotations();
    if (paramAnns.length == 0) {
        return CastUtils.cast(Collections.emptyList(), Parameter.class);
    }
    Class<?>[] types = resourceMethod.getParameterTypes();
    List<Parameter> params = new ArrayList<>(paramAnns.length);
    for (int i = 0; i < paramAnns.length; i++) {
        Parameter p = getParameter(i, paramAnns[i], types[i]);
        params.add(p);
    }
    return params;
}
 
Example 13
@Test
public void shouldReturnArgumentToString()
		throws NoSuchMethodException, SecurityException {
	Method method = AnnotationMockClass.class
			.getMethod("getAnnotationForArgumentToString", Long.class);
	Annotation annotation = method.getParameterAnnotations()[0][0];
	if (annotation instanceof SpanTag) {
		String resolvedValue = this.handler.resolveTagValue((SpanTag) annotation, 15);
		assertThat(resolvedValue).isEqualTo("15");
	}
	else {
		fail("Annotation was not SleuthSpanTag");
	}
}
 
Example 14
Source Project: dubbox   File: JValidator.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean hasConstraintParameter(Method method) {
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    if (parameterAnnotations != null && parameterAnnotations.length > 0) {
        for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 15
@Test
public void testSupportAndResolve() throws NoSuchMethodException {
    Method method = MappingsController.class.getMethod("handleSession", Map.class);
    MethodParameter methodParameter = new MethodParameter(
            method,
            0,
            Map.class,
            method.getParameterAnnotations()[0]
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("intent");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    assertSame(envelope.getSession().getAttributes(), resolver.resolve(input).get());
}
 
Example 16
private String generateActionDefinition( String actionName,
                                         Method actionImplementation,
                                         String transferUnit,
                                         boolean registerAction ) {

    log.info("Generating method implementation for action '" + actionName + "'");

    String[] paramNames = new String[actionImplementation.getParameterTypes().length];
    String[] paramTypes = new String[actionImplementation.getParameterTypes().length];

    Annotation[][] parameterAnnotations = actionImplementation.getParameterAnnotations();
    for (int i = 0; i < parameterAnnotations.length; i++) {
        Class<?> paramType = actionImplementation.getParameterTypes()[i];

        Annotation[] currentParamAnnotations = parameterAnnotations[i];

        Parameter paramAnnotation = null;
        for (int j = 0; j < currentParamAnnotations.length; j++) {
            if (currentParamAnnotations[j] instanceof Parameter) {
                paramAnnotation = (Parameter) currentParamAnnotations[j];
                break;
            }
        }

        if (paramAnnotation == null) {
            throw new BuildException("No @Parameter annotation for one of the parameters of action method "
                                     + actionImplementation.toString());
        }

        paramNames[i] = paramAnnotation.name();

        if (paramType.isArray() && paramType.getComponentType().isEnum()) {
            //array of enums should be represented by array of String in the generated stub
            paramTypes[i] = "String[]";
        } else if (paramType.isEnum()) {
            //enums should be represented by Strings in the generated stub
            paramTypes[i] = "String";
        } else {
            paramTypes[i] = paramType.getSimpleName();
        }
    }

    //parameters and arguments
    if (paramNames.length != paramTypes.length) {
        throw new BuildException("Parameter names count different than parameter types count for action method "
                                 + actionImplementation.toString());
    }

    Annotation deprecatedAnnotation = actionImplementation.getAnnotation(Deprecated.class);
    boolean isDeprecated = (deprecatedAnnotation != null);

    try {
        return new MethodTemplateProcessor(actionImplementation, actionName, paramNames, registerAction,
                                           paramTypes, transferUnit, isDeprecated).processTemplate();
    } catch (IOException ioe) {
        throw new BuildException(ioe);
    }
}
 
Example 17
Source Project: Spork   File: NullabilityTests.java    License: Apache License 2.0 4 votes vote down vote up
private static Annotation[] getFirstMethodArgumentAnnotations(String methodName) throws NoSuchMethodException {
	Method method = Testable.class.getDeclaredMethod(methodName, String.class);
	assertThat(method.getParameterAnnotations().length, is(1));
	return method.getParameterAnnotations()[0];
}
 
Example 18
/**
 * Create list of {@link Parameter} .
 *
 * @param resourceClass
 *         class
 * @param method
 *         See {@link java.lang.reflect.Method}
 * @return list of {@link Parameter}
 */
private List<Parameter> createMethodParameters(Class<?> resourceClass, Method method) {
    Class<?>[] parameterClasses = method.getParameterTypes();
    if (parameterClasses.length > 0) {
        Type[] parameterGenTypes = method.getGenericParameterTypes();
        Annotation[][] annotations = method.getParameterAnnotations();

        List<Parameter> methodParameters = new ArrayList<>(parameterClasses.length);
        boolean classEncoded = getClassAnnotation(resourceClass, Encoded.class) != null;
        boolean methodEncoded = getMethodAnnotation(method, resourceClass, Encoded.class, false) != null;
        for (int i = 0; i < parameterClasses.length; i++) {
            String defaultValue = null;
            Annotation parameterAnnotation = null;
            boolean encoded = false;

            for (int j = 0; j < annotations[i].length; j++) {
                Annotation annotation = annotations[i][j];
                Class<?> annotationType = annotation.annotationType();
                if (RESOURCE_METHOD_PARAMETER_ANNOTATIONS.contains(annotationType.getName())) {
                    if (parameterAnnotation != null) {
                        String msg = String.format(
                                "JAX-RS annotations on one of method parameters of resource %s, method %s are equivocality. Annotations: %s and %s can't be applied to one parameter",
                                toString(), method.getName(), parameterAnnotation, annotation);
                        throw new RuntimeException(msg);
                    }
                    parameterAnnotation = annotation;
                } else if (annotationType == Encoded.class) {
                    encoded = true;
                } else if (annotationType == DefaultValue.class) {
                    defaultValue = ((DefaultValue)annotation).value();
                }
            }

            Parameter methodParameter = new MethodParameter(
                    parameterAnnotation,
                    annotations[i],
                    parameterClasses[i],
                    parameterGenTypes[i],
                    defaultValue,
                    encoded || methodEncoded || classEncoded);
            methodParameters.add(methodParameter);
        }

        return methodParameters;
    }

    return Collections.emptyList();
}
 
Example 19
Source Project: mdw   File: SwaggerAnnotationsReader.java    License: Apache License 2.0 4 votes vote down vote up
private void read(ReaderContext context) {
    final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class);
    if (swaggerDefinition != null) {
        readSwaggerConfig(swaggerDefinition);
    }
    for (Method method : context.getCls().getMethods()) {
        if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) {
            continue;
        }
        final Operation operation = new Operation();
        String operationPath = null;
        String httpMethod = null;

        final Type[] genericParameterTypes = method.getGenericParameterTypes();
        final Annotation[][] paramAnnotations = method.getParameterAnnotations();

        // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension
        // for (ReaderExtension extension : ReaderExtensions.getExtensions()) {
        for (ReaderExtension extension : getExtensions()) {
            if (operationPath == null) {
                operationPath = extension.getPath(context, method);
            }
            if (httpMethod == null) {
                httpMethod = extension.getHttpMethod(context, method);
            }
            if (operationPath == null || httpMethod == null) {
                continue;
            }

            if (extension.isReadable(context)) {
                extension.setDeprecated(operation, method);
                extension.applyConsumes(context, operation, method);
                extension.applyProduces(context, operation, method);
                extension.applyOperationId(operation, method);
                extension.applySummary(operation, method);
                extension.applyDescription(operation, method);
                extension.applySchemes(context, operation, method);
                extension.applySecurityRequirements(context, operation, method);
                extension.applyTags(context, operation, method);
                extension.applyResponses(context, operation, method);
                extension.applyImplicitParameters(context, operation, method);
                for (int i = 0; i < genericParameterTypes.length; i++) {
                    extension.applyParameters(context, operation, genericParameterTypes[i], paramAnnotations[i]);
                }
            }
        }

        if (httpMethod != null && operationPath != null) {
            if (operation.getResponses() == null) {
                operation.defaultResponse(new Response().description("OK"));
            }
            else {
                for (String k : operation.getResponses().keySet()) {
                    if (k.equals("200")) {
                        Response response = operation.getResponses().get(k);
                        if ("successful operation".equals(response.getDescription()))
                            response.setDescription("OK");
                    }
                }
            }

            final Map<String,String> regexMap = new HashMap<>();
            final String parsedPath = PathUtils.parsePath(operationPath, regexMap);

            if (parsedPath != null) {
                // check for curly path params
                for (String seg : parsedPath.split("/")) {
                    if (seg.startsWith("{") && seg.endsWith("}")) {
                        String segName = seg.substring(1, seg.length() - 1);
                        boolean declared = false;
                        for (Parameter opParam : operation.getParameters()) {
                            if ("path".equals(opParam.getIn()) && segName.equals(opParam.getName())) {
                                declared = true;
                                break;
                            }
                        }
                        if (!declared) {
                            // add it for free
                            PathParameter pathParam = new PathParameter();
                            pathParam.setName(segName);
                            pathParam.setRequired(false);
                            pathParam.setDefaultValue("");
                            operation.parameter(pathParam);
                        }
                    }
                }
            }


            Path path = swagger.getPath(parsedPath);
            if (path == null) {
                path = new Path();
                swagger.path(parsedPath, path);
            }
            path.set(httpMethod.toLowerCase(), operation);
        }
    }
}
 
Example 20
Source Project: cxf   File: ClientProxyImpl.java    License: Apache License 2.0 4 votes vote down vote up
protected static Annotation[] getMethodAnnotations(Method aMethod, int bodyIndex) {
    return aMethod == null || bodyIndex == -1 ? new Annotation[0]
        : aMethod.getParameterAnnotations()[bodyIndex];
}