java.lang.reflect.Parameter#getAnnotation ( )源码实例Demo

下面列出了java.lang.reflect.Parameter#getAnnotation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: selenium-jupiter   文件: SelenideDriverHandler.java
public SelenideConfig getSelenideConfig(Parameter parameter,
        Optional<Object> testInstance) throws IllegalAccessException {

    SelenideConfig config = new SelenideConfig();
    if (parameter != null) {
        // @SelenideConfiguration as parameter
        SelenideConfiguration selenideConfiguration = parameter
                .getAnnotation(SelenideConfiguration.class);
        if (selenideConfiguration != null) {
            config.browser(selenideConfiguration.browser());
            config.headless(selenideConfiguration.headless());
            config.browserBinary(selenideConfiguration.browserBinary());
        }

        // @SelenideConfiguration as field
        SelenideConfig globalConfig = annotationsReader
                .getFromAnnotatedField(testInstance,
                        SelenideConfiguration.class, SelenideConfig.class);
        if (globalConfig != null) {
            config = globalConfig;
        }
    }

    return config;
}
 
源代码2 项目: flow   文件: ComponentEventBusUtil.java
/**
 * Checks if the given constructor can be used when firing a
 * {@link ComponentEvent} based on a {@link DomEvent}.
 *
 * @param constructor
 *            the constructor to check
 * @return <code>true</code> if the constructor can be used,
 *         <code>false</code> otherwise
 */
public static boolean isDomEventConstructor(Constructor<?> constructor) {
    if (constructor.getParameterCount() < 2) {
        return false;
    }
    if (!Component.class
            .isAssignableFrom(constructor.getParameterTypes()[0])) {
        return false;
    }
    if (constructor.getParameterTypes()[1] != boolean.class) {
        return false;
    }
    for (int param = 2; param < constructor.getParameterCount(); param++) {
        Parameter p = constructor.getParameters()[param];

        if (p.getAnnotation(EventData.class) == null) {
            return false;
        }
    }

    return true;
}
 
源代码3 项目: flow   文件: ComponentEventBusUtil.java
/**
 * Scans the event type and forms a map of event data expression (for
 * {@link com.vaadin.flow.dom.DomListenerRegistration#addEventData(String)}
 * ) to Java type, with the same order as the parameters for the event
 * constructor (as returned by {@link #getEventConstructor(Class)}).
 *
 * @return a map of event data expressions, in the order defined by the
 *         component event constructor parameters
 */
private static LinkedHashMap<String, Class<?>> findEventDataExpressions(
        Constructor<? extends ComponentEvent<?>> eventConstructor) {
    LinkedHashMap<String, Class<?>> eventDataExpressions = new LinkedHashMap<>();
    // Parameter 0 is always "Component source"
    // Parameter 1 is always "boolean fromClient"
    for (int i = 2; i < eventConstructor.getParameterCount(); i++) {
        Parameter p = eventConstructor.getParameters()[i];
        EventData eventData = p.getAnnotation(EventData.class);
        if (eventData == null || eventData.value().isEmpty()) {
            // The parameter foo of the constructor Bar(Foo foo) has no
            // @DomEvent, or its value is empty."
            throw new IllegalArgumentException(String.format(
                    "The parameter %s of the constructor %s has no @%s, or the annotation value is empty",
                    p.getName(), eventConstructor.toString(),
                    EventData.class.getSimpleName()));
        }
        eventDataExpressions.put(eventData.value(),p.getType());
    }
    return eventDataExpressions;
}
 
源代码4 项目: flink   文件: FunctionMappingExtractor.java
private static Optional<FunctionArgumentTemplate> tryExtractInputGroupArgument(Method method, int paramPos) {
	final Parameter parameter = method.getParameters()[paramPos];
	final DataTypeHint hint = parameter.getAnnotation(DataTypeHint.class);
	if (hint != null) {
		final DataTypeTemplate template = DataTypeTemplate.fromAnnotation(hint, null);
		if (template.inputGroup != null) {
			return Optional.of(FunctionArgumentTemplate.of(template.inputGroup));
		}
	}
	return Optional.empty();
}
 
源代码5 项目: msf4j   文件: EndpointValidator.java
private boolean validateOnStringMethod(Object webSocketEndpoint)
        throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
    EndpointDispatcher dispatcher = new EndpointDispatcher();
    Method method;
    if (dispatcher.getOnStringMessageMethod(webSocketEndpoint).isPresent()) {
        method = dispatcher.getOnStringMessageMethod(webSocketEndpoint).get();
    } else {
        return true;
    }
    validateReturnType(method);
    boolean foundPrimaryString = false;
    for (Parameter parameter: method.getParameters()) {
        Class<?> paraType = parameter.getType();
        if (paraType == String.class) {
            if (parameter.getAnnotation(PathParam.class) == null) {
                if (foundPrimaryString) {
                    throw new WebSocketMethodParameterException("Invalid parameter found on text message method: " +
                                                                        "More than one string parameter without " +
                                                                        "@PathParam annotation.");
                }
                foundPrimaryString = true;
            }
        } else if (paraType != WebSocketConnection.class) {
            throw new WebSocketMethodParameterException("Invalid parameter found on text message method: " +
                                                                paraType);
        }
    }
    return foundPrimaryString;
}
 
源代码6 项目: o2oa   文件: ApiBuilder.java
private JaxrsPathParameter jaxrsPathParameter(Class<?> clz, Method method, Parameter parameter) throws Exception {
	JaxrsParameterDescribe jaxrsParameterDescribe = parameter.getAnnotation(JaxrsParameterDescribe.class);
	PathParam pathParam = parameter.getAnnotation(PathParam.class);
	JaxrsPathParameter o = new JaxrsPathParameter();
	o.setName(pathParam.value());
	if (null != jaxrsParameterDescribe) {
		o.setDescription(jaxrsParameterDescribe.value());
	} else {
		logger.print("类: {}, 方法: {} ,未设置参数 {} 的JaxrsParameterDescribe.", clz.getName(), method.getName(),
				pathParam.value());
		o.setDescription("");
	}
	o.setType(this.getJaxrsParameterType(parameter));
	return o;
}
 
源代码7 项目: fastquery   文件: TypeUtil.java
/**
 * 查询标识有指定注解的参数
 *
 * @param clazz      待查找的类型
 * @param parameters 参数类型集
 * @return 参数类型
 */
public static Parameter findParameter(Class<? extends Annotation> clazz, Parameter[] parameters) {
    for (Parameter parameter : parameters) {
        if (parameter.getAnnotation(clazz) != null) {
            return parameter;
        }
    }
    return null;
}
 
源代码8 项目: graphql-spqr   文件: AnnotatedArgumentBuilder.java
protected Object defaultValue(Parameter parameter, AnnotatedType parameterType, GlobalEnvironment environment) {

        GraphQLArgument meta = parameter.getAnnotation(GraphQLArgument.class);
        if (meta == null) return null;
        try {
            return defaultValueProvider(meta.defaultValueProvider(), environment)
                    .getDefaultValue(parameter, environment.getMappableInputType(parameterType), ReservedStrings.decode(environment.messageBundle.interpolate(meta.defaultValue())));
        } catch (ReflectiveOperationException e) {
            throw new IllegalArgumentException(
                    meta.defaultValueProvider().getName() + " must expose a public default constructor, or a constructor accepting " + GlobalEnvironment.class.getName(), e);
        }
    }
 
源代码9 项目: o2oa   文件: ApiBuilder.java
private JaxrsQueryParameter jaxrsQueryParameter(Class<?> clz, Method method, Parameter parameter) {
	JaxrsParameterDescribe jaxrsParameterDescribe = parameter.getAnnotation(JaxrsParameterDescribe.class);
	QueryParam queryParam = parameter.getAnnotation(QueryParam.class);
	JaxrsQueryParameter o = new JaxrsQueryParameter();
	if (null != jaxrsParameterDescribe) {
		o.setDescription(jaxrsParameterDescribe.value());
	} else {
		logger.print("类: {}, 方法: {} ,未设置参数 {} 的JaxrsParameterDescribe.", clz.getName(), method.getName(),
				queryParam.value());
		o.setDescription("");
	}
	o.setName(queryParam.value());
	o.setType(this.simpleType(parameter.getType().getName()));
	return o;
}
 
源代码10 项目: selenium-jupiter   文件: OperaDriverHandler.java
@Override
public MutableCapabilities getOptions(Parameter parameter,
        Optional<Object> testInstance)
        throws IOException, IllegalAccessException {
    OperaOptions operaOptions = new OperaOptions();

    if (parameter != null) {
        // @Arguments
        Arguments arguments = parameter.getAnnotation(Arguments.class);
        if (arguments != null) {
            stream(arguments.value()).forEach(operaOptions::addArguments);
        }

        // @Extensions
        Extensions extensions = parameter.getAnnotation(Extensions.class);
        if (extensions != null) {
            for (String extension : extensions.value()) {
                operaOptions.addExtensions(getExtension(extension));
            }
        }

        // @Binary
        Binary binary = parameter.getAnnotation(Binary.class);
        if (binary != null) {
            operaOptions.setBinary(binary.value());
        }

        // @Options
        OperaOptions optionsFromAnnotatedField = annotationsReader
                .getFromAnnotatedField(testInstance, Options.class,
                        OperaOptions.class);
        if (optionsFromAnnotatedField != null) {
            operaOptions = optionsFromAnnotatedField.merge(operaOptions);
        }
    }

    return operaOptions;
}
 
源代码11 项目: oxygen   文件: MultipartParamBinder.java
@Override
public DataBinder build(Parameter parameter) {
  DataBinder dataBinder = new DataBinder();
  dataBinder.setType(parameter.getType());
  dataBinder.setName(parameter.getName());
  MultipartParam param = parameter.getAnnotation(MultipartParam.class);
  if (param != null && param.value().length() > 0) {
    dataBinder.setName(param.value());
  }
  dataBinder.setFunc(ctx -> ctx.request().getMultipartItem(dataBinder.getName()));
  return dataBinder;
}
 
源代码12 项目: msf4j   文件: EndpointValidator.java
private boolean validateOnPongMethod(Object webSocketEndpoint)
        throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
    EndpointDispatcher dispatcher = new EndpointDispatcher();
    Method method;
    if (dispatcher.getOnPongMessageMethod(webSocketEndpoint).isPresent()) {
        method = dispatcher.getOnPongMessageMethod(webSocketEndpoint).get();
    } else {
        return true;
    }
    validateReturnType(method);
    boolean foundPrimaryPong = false;
    for (Parameter parameter: method.getParameters()) {
        Class<?> paraType = parameter.getType();
        if (paraType == String.class) {
            if (parameter.getAnnotation(PathParam.class) == null) {
                throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
                                                                    "string parameter without " +
                                                                    "@PathParam annotation.");
            }
        } else if (paraType == PongMessage.class) {
            if (foundPrimaryPong) {
                throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
                                                                    "only one PongMessage should be declared.");
            }
            foundPrimaryPong = true;
        } else if (paraType != WebSocketConnection.class) {
            throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
                                                                paraType);
        }
    }
    return foundPrimaryPong;
}
 
源代码13 项目: o2oa   文件: DescribeBuilder.java
private JaxrsQueryParameter jaxrsQueryParameter(Class<?> clz, Method method, Parameter parameter) {
	JaxrsParameterDescribe jaxrsParameterDescribe = parameter.getAnnotation(JaxrsParameterDescribe.class);
	QueryParam queryParam = parameter.getAnnotation(QueryParam.class);
	JaxrsQueryParameter o = new JaxrsQueryParameter();
	if (null != jaxrsParameterDescribe) {
		o.setDescription(jaxrsParameterDescribe.value());
	} else {
		logger.print("类: {}, 方法: {} ,未设置参数 {} 的JaxrsParameterDescribe.", clz.getName(), method.getName(),
				queryParam.value());
		o.setDescription("");
	}
	o.setName(queryParam.value());
	o.setType(this.simpleType(parameter.getType().getName()));
	return o;
}
 
源代码14 项目: pippo   文件: ControllerUtils.java
/**
 * Returns the name of a parameter.
 *
 * @param parameter
 * @return the name of a parameter.
 */
public static String getParameterName(Parameter parameter) {
    // identify parameter name and pattern from controllerMethod signature
    String methodParameterName = parameter.getName();
    if (parameter.isAnnotationPresent(Param.class)) {
        Param param = parameter.getAnnotation(Param.class);
        if (!StringUtils.isNullOrEmpty(param.value())) {
            methodParameterName = param.value();
        }
    }

    return methodParameterName;
}
 
源代码15 项目: spring-cloud-sockets   文件: ServiceMethodInfo.java
private void findPayloadParameter(){
	if(this.method.getParameterCount() == 0){
		throw new IllegalStateException("Service methods must have at least one receiving parameter");
	}

	else if(this.method.getParameterCount() == 1){
		this.payloadParameter = new MethodParameter(this.method, 0);
	}
	int payloadAnnotations = Flux.just(this.method.getParameters())
			.filter(parameter -> parameter.getAnnotation(Payload.class) != null)
			.reduce(0, (a, parameter) -> { return a+1; })
			.block();
	if(payloadAnnotations > 1){
		throw new IllegalStateException("Service methods can have at most one @Payload annotated parameters");
	}

	for(int i=0; i<this.method.getParameters().length; i++){
		Parameter p = this.method.getParameters()[i];
		if(p.getAnnotation(Payload.class) != null){
			this.payloadParameter = new MethodParameter(this.method, i);
			break;
		}
	}
	if(this.payloadParameter == null){
		throw new IllegalStateException("Service methods annotated with more than one parameter must declare one @Payload parameter");
	}
	resolvePayloadType();
}
 
@Test
public void parseParameter() throws NoSuchMethodException {
  Class<ParamAnnotationResource> paramAnnotationResourceClass = ParamAnnotationResource.class;
  OasContext oasContext = new OasContext(null);
  OperationContext operationContext;
  ParameterContext parameterContext;

  RequestParamAnnotationProcessor requestParamAnnotationProcessor = new RequestParamAnnotationProcessor();
  Method requestParamMethod = paramAnnotationResourceClass.getMethod("requestParam", String.class);
  Parameter requestParamMethodParam = requestParamMethod.getParameters()[0];
  RequestParam requestParamAnnotation = requestParamMethodParam
      .getAnnotation(RequestParam.class);
  operationContext = new OperationContext(requestParamMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestParamMethodParam);
  requestParamAnnotationProcessor.process(requestParamAnnotation, parameterContext);
  io.swagger.v3.oas.models.parameters.Parameter oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertNull(oasParameter.getSchema().getDefault());

  PathVariableAnnotationProcessor pathVariableAnnotationProcessor = new PathVariableAnnotationProcessor();
  Method pathVariableMethod = paramAnnotationResourceClass.getMethod("pathVariable", String.class);
  Parameter pathVariableMethodParam = pathVariableMethod.getParameters()[0];
  PathVariable pathVariableAnnotation = pathVariableMethodParam
      .getAnnotation(PathVariable.class);
  operationContext = new OperationContext(pathVariableMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, pathVariableMethodParam);
  pathVariableAnnotationProcessor.process(pathVariableAnnotation, parameterContext);
  parameterContext.toParameter();
  Assert.assertTrue(parameterContext.isRequired());

  RequestPartAnnotationProcessor requestPartAnnotationProcessor = new RequestPartAnnotationProcessor();
  Method requestPartMethod = paramAnnotationResourceClass.getMethod("requestPart", MultipartFile.class);
  Parameter requestPartMethodParam = requestPartMethod.getParameters()[0];
  RequestPart requestPartParamAnnotation = requestPartMethodParam
      .getAnnotation(RequestPart.class);
  operationContext = new OperationContext(requestPartMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestPartMethodParam);
  requestPartAnnotationProcessor.process(requestPartParamAnnotation, parameterContext);
  oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertEquals(FileSchema.class, oasParameter.getSchema().getClass());

  RequestHeaderAnnotationProcessor requestHeaderAnnotationProcessor = new RequestHeaderAnnotationProcessor();
  Method requestHeaderMethod = paramAnnotationResourceClass.getMethod("requestHeader", String.class);
  Parameter requestHeaderMethodParam = requestHeaderMethod.getParameters()[0];
  RequestHeader requestHeaderParamAnnotation = requestHeaderMethodParam
      .getAnnotation(RequestHeader.class);
  operationContext = new OperationContext(requestPartMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestHeaderMethodParam);
  requestHeaderAnnotationProcessor.process(requestHeaderParamAnnotation, parameterContext);
  oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertNull(oasParameter.getSchema().getDefault());

  RequestBodyAnnotationProcessor requestBodyAnnotationProcessor = new RequestBodyAnnotationProcessor();
  Method requestBodyMethod = paramAnnotationResourceClass.getMethod("requestBody", String.class);
  Parameter requestBodyMethodParam = requestBodyMethod.getParameters()[0];
  RequestBody requestBodyParamAnnotation = requestBodyMethodParam
      .getAnnotation(RequestBody.class);
  operationContext = new OperationContext(requestBodyMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestBodyMethodParam);
  requestBodyAnnotationProcessor.process(requestBodyParamAnnotation, parameterContext);
  parameterContext.toParameter();
  Assert.assertTrue(parameterContext.isRequired());
}
 
源代码17 项目: pdfcompare   文件: TempDirectoryExtension.java
@Override
public boolean supportsParameter(ParameterContext paramContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = paramContext.getParameter();
    return parameter.getAnnotation(TempDirectory.class) != null && Path.class.equals(parameter.getType());
}
 
源代码18 项目: GreenSummer   文件: LogOperationAspect.java
private StringBuilder extractArguments(
    Method method,
    Object[] args) {
  StringBuilder theSB = new StringBuilder();
  try {
    Parameter[] parameters = method.getParameters();
    boolean added = false;
    if (parameters != null && parameters.length > 0) {
      theSB.append(": ");
      for (int i = 0; i < parameters.length; i++) {
        Parameter parameter = parameters[i];
        if (parameter.getAnnotation(DontLog.class) == null && args[i] != null) {
          final Class<?> parameterType = parameter.getType();
          final boolean isLogable = Logable.class.isAssignableFrom(parameterType);
          //@formatter:off
                      if (
                          parameterType.isPrimitive()
                          || parameterType.isEnum()
                          || CharSequence.class.isAssignableFrom(parameterType)
                          || isLogable
                          ) {
                          addParameterName(theSB, added, parameter);
                          if(isLogable) {
                            theSB.append(((Logable)args[i]).formatted());
                          } else {
                            theSB.append(args[i].toString());
                          }
                          added = true;
                      } else if (
                              parameterType.isArray()
                              && (
                                  parameterType.getComponentType().isPrimitive()
                                  || parameterType.getComponentType().isEnum()
                                  || CharSequence.class.isAssignableFrom(parameterType.getComponentType())
                              )
                      ) {
                          addParameterName(theSB, added, parameter);
                          int lenght = Array.getLength(args[i]);
                          StringJoiner st = new StringJoiner(",");
                          for(int j = 0 ; j < lenght ; j++) {
                            st.add(Array.get(args[i], j).toString());
                          }
                          theSB.append(st.toString());
                          added = true;
                      }
                      //@formatter:on
        }
      }
    }
  } catch (Exception e) {
    log.error("Error extracting arguments from method", e);
  }
  return theSB;
}
 
源代码19 项目: graphql-spqr   文件: AnnotatedArgumentBuilder.java
protected String getArgumentDescription(Parameter parameter, AnnotatedType parameterType, MessageBundle messageBundle) {
    GraphQLArgument meta = parameter.getAnnotation(GraphQLArgument.class);
    return meta != null ? messageBundle.interpolate(meta.description()) : null;
}
 
源代码20 项目: Poseidon   文件: PoseidonLegoSet.java
private void resolveInjectableConstructorDependencies(Constructor<?> constructor, Object[] initParams, int offset, Optional<Request> request) throws MissingInformationException, ElementNotFoundException {
    for (int i = offset; i < constructor.getParameterCount(); i++) {
        final Parameter constructorParameter = constructor.getParameters()[i];
        final RequestAttribute requestAttribute = constructorParameter.getAnnotation(RequestAttribute.class);
        final com.flipkart.poseidon.datasources.ServiceClient serviceClientAttribute = constructorParameter.getAnnotation(com.flipkart.poseidon.datasources.ServiceClient.class);
        final SystemDataSource systemDataSourceAttribute = constructorParameter.getAnnotation(SystemDataSource.class);
        if (requestAttribute != null) {
            final String attributeName = StringUtils.isNullOrEmpty(requestAttribute.value()) ? constructorParameter.getName() : requestAttribute.value();
            initParams[i] = request.map(r -> r.getAttribute(attributeName)).map(attr -> {
                if (constructorParameter.getType().isAssignableFrom(attr.getClass())) {
                    return attr;
                } else {
                    return mapper.convertValue(attr, mapper.constructType(constructorParameter.getParameterizedType()));
                }
            }).orElse(null);
        } else if (serviceClientAttribute != null) {
            ServiceClient serviceClient = serviceClientsByName.get(constructor.getParameterTypes()[i].getName());
            if (serviceClient == null) {
                throw new ElementNotFoundException("Unable to find ServiceClient for class = " + constructor.getParameterTypes()[i]);
            }
            initParams[i] = serviceClient;
        } else if (systemDataSourceAttribute != null) {
            final DataSource<?> systemDataSource = systemDataSources.get(systemDataSourceAttribute.value());
            if (systemDataSource == null) {
                throw new ElementNotFoundException("Unable to find SystemDataSource for id = " + systemDataSourceAttribute.value());
            }
            initParams[i] = systemDataSource;
        } else {
            final Qualifier qualifier = constructorParameter.getAnnotation(Qualifier.class);
            String beanName = null;
            if (qualifier != null && !StringUtils.isNullOrEmpty(qualifier.value())) {
                beanName = qualifier.value();
            }

            initParams[i] = beanName == null ? context.getBean(constructor.getParameterTypes()[i]) : context.getBean(beanName, constructor.getParameterTypes()[i]);
            if (initParams[i] == null) {
                throw new MissingInformationException("Unmet dependency for constructor " + constructor.getName() + ": " + constructor.getParameterTypes()[i].getCanonicalName());
            }
        }
    }
}