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

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

源代码1 项目: spring-openapi   文件: OperationsTransformer.java
private Schema createSchemaFromParameter(Parameter parameter, String parameterName) {
	Schema schema;
	Class<?> clazz = parameter.getType();
	Annotation[] annotations = parameter.getAnnotations();

	if (clazz.isPrimitive()) {
		schema = schemaGeneratorHelper.parseBaseTypeSignature(clazz, annotations);
	} else if (clazz.isArray()) {
		schema = schemaGeneratorHelper.parseArraySignature(clazz.getComponentType(), null, annotations);
	} else if (clazz.isAssignableFrom(List.class)) {
		if (parameter.getParameterizedType() instanceof ParameterizedType) {
			Class<?> listGenericParameter = (Class<?>)((ParameterizedType) parameter.getParameterizedType()).getActualTypeArguments()[0];
			return schemaGeneratorHelper.parseArraySignature(listGenericParameter, null, annotations);
		}

		throw new IllegalArgumentException(String.format("List [%s] not being parametrized type.", parameterName));
	} else {
		schema = schemaGeneratorHelper.parseClassRefTypeSignature(clazz, annotations, null);
	}
	return schema;
}
 
源代码2 项目: spring-openapi   文件: OperationsTransformer.java
private void fillParameterInfo(AbstractSerializableParameter<?> oasParameter, Parameter parameter, String parameterName) {
	Class<?> clazz = parameter.getType();
	Annotation[] annotations = parameter.getAnnotations();

	if (clazz.isPrimitive()) {
		setParameterDetails(oasParameter, clazz, annotations);
	} else if (clazz.isArray()) {
		oasParameter.setProperty(parseArraySignatureForParameter(clazz.getComponentType(), annotations));
	} else if (clazz.isAssignableFrom(List.class)) {
		if (!(parameter.getParameterizedType() instanceof ParameterizedType)) {
			throw new IllegalArgumentException(String.format("List [%s] not being parametrized type.", parameterName));
		}
		Class<?> listGenericParameter = (Class<?>) ((ParameterizedType) parameter.getParameterizedType()).getActualTypeArguments()[0];
		oasParameter.setProperty(parseArraySignature(listGenericParameter, null, annotations));
	} else {
		setParameterDetails(oasParameter, clazz, annotations);
	}
}
 
源代码3 项目: CheckPoint   文件: AnnotationScanner.java
/**
 * Gets parameter from method with annotation.
 *
 * @param parentClass     the parent class
 * @param method          the method
 * @param annotationClass the annotation class
 * @return the parameter from method with annotation
 */
public List<DetailParam> getParameterFromMethodWithAnnotation(Class<?> parentClass, Method method, Class<?> annotationClass) {
    List<DetailParam> params = new ArrayList<>();
    if (method.getParameterCount() < 1) {
        return params;
    }

    for (Parameter param : method.getParameters()) {

        Annotation[] annotations = param.getAnnotations();

        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(annotationClass)) {
                params.add(new DetailParam(param.getType(), method, parentClass));
                break;
            }
        }
    }
    return params;
}
 
@Override
public String[] apply(Method method) {
    List<String> parameterNames = new ArrayList<>();
    for(Parameter parameter : method.getParameters()){
        String parameterName = null;
        for (Annotation annotation : parameter.getAnnotations()) {
            parameterName = getName(annotation);
            if(parameterName != null && !parameterName.isEmpty()){
                break;
            }
        }
        if(parameterName == null){
            parameterName = parameter.getName();
        }
        parameterNames.add(parameterName);
    }
    return parameterNames.toArray(new String[0]);
}
 
@Override
public void check(Method method) throws CodeCheckException {
	for (Parameter parameter : method.getParameters()) {
		Annotation[] annotations = parameter.getAnnotations();
		for (Annotation annotation : annotations) {
			if (excepts.contains(annotation.annotationType())) {
				continue;
			}
			Constraint constraint = annotation.annotationType().getAnnotation(Constraint.class);
			if (constraint != null) {
				for (Class<?> klass : getAllSuitableClasses(parameter.getType(), constraint)) {
					if (!isSuitable(parameter.getType(), klass)) {
						throw new CodeCheckException("方法", ReflectUtil.fullName(method), "的参数", parameter.getName(), "的类型必须是", klass
							.getCanonicalName(), "或者其子类");
					}
				}
			}
		}
	}
}
 
源代码6 项目: socket   文件: ApiUtil.java
/**
 * 获取字段的命名
 *
 * @param parameter 要获取命名的字段
 * @return 指定字段的命名
 */
private static String getParamName(Parameter parameter) throws ParamterNoNamingException {
    Annotation[] annotations = parameter.getAnnotations();
    GeneralParam generalParam = null;
    Context context = null;
    for (Annotation annotation : annotations) {
        if (annotation instanceof GeneralParam) {
            generalParam = (GeneralParam) annotation;
            break;
        } else if (annotation instanceof Context) {
            context = (Context) annotation;
            break;
        }
    }

    if (generalParam != null && !generalParam.value().trim().isEmpty()) {
        return generalParam.value();
    } else if (context != null) {
        return "Context";
    } else {
        throw new ParamterNoNamingException(parameter);
    }
}
 
源代码7 项目: socket   文件: ApiUtil.java
/**
 * 判断参数是否是Context参数
 *
 * @param parameter 参数
 * @return 如果返回true说明此参数是Context类型
 */
private static boolean isContextParam(Parameter parameter) {
    Annotation[] annotations = parameter.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation instanceof Context) {
            return true;
        }
    }
    return false;
}
 
源代码8 项目: baratine   文件: InjectionPoint.java
static <T> InjectionPoint<T> of(Parameter p)
{
  return new InjectionPointImpl<>((Key<T>) Key.of(p),
      p.getParameterizedType(),
      p.getName(),
      p.getAnnotations(),
      p.getDeclaringExecutable().getDeclaringClass());
}
 
源代码9 项目: nubes   文件: MethodVisitor.java
private void createParamAnnotationHandlers(Parameter p) {
  Annotation[] paramAnnotations = p.getAnnotations();
  if (paramAnnotations != null) {
    for (Annotation annotation : paramAnnotations) {
      Set<Handler<RoutingContext>> paramHandler = config.getAnnotationHandler(annotation.annotationType());
      if (paramHandler != null) {
        paramsHandlers.addAll(paramHandler);
      }
    }
  }
}
 
源代码10 项目: dropwizard-guicey   文件: TestParametersSupport.java
@Override
@SuppressWarnings("checkstyle:ReturnCount")
public boolean supportsParameter(final ParameterContext parameterContext,
                                 final ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = parameterContext.getParameter();
    if (parameter.getAnnotations().length > 0) {
        if (AnnotationSupport.isAnnotated(parameter, Jit.class)) {
            return true;
        } else if (!isQualifierAnnotation(parameter.getAnnotations())) {
            // if any other annotation declared on the parameter - skip it (possibly other extension's parameter)
            return false;
        }
    }

    final Class<?> type = parameter.getType();
    if (Application.class.isAssignableFrom(type) || Configuration.class.isAssignableFrom(type)) {
        // special case when exact app or configuration class used
        return true;
    } else {
        for (Class<?> cls : supportedClasses) {
            if (type.equals(cls)) {
                return true;
            }
        }
    }

    // declared guice binding (by class only)
    return getInjector(extensionContext)
            .map(it -> it.getExistingBinding(getKey(parameter)) != null)
            .orElse(false);
}
 
源代码11 项目: dropwizard-guicey   文件: TestParametersSupport.java
private Key<?> getKey(final Parameter parameter) {
    final Key<?> key;
    if (parameter.getAnnotations().length > 0
            && !AnnotationSupport.isAnnotated(parameter, Jit.class)) {
        // qualified bean
        key = Key.get(parameter.getParameterizedType(), parameter.getAnnotations()[0]);
    } else {
        key = Key.get(parameter.getParameterizedType());
    }
    return key;
}
 
源代码12 项目: spring-analysis-note   文件: ResolvableMethod.java
private String formatParameter(Parameter param) {
	Annotation[] anns = param.getAnnotations();
	return (anns.length > 0 ?
			Arrays.stream(anns).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param :
			param.toString());
}
 
源代码13 项目: spring-analysis-note   文件: ResolvableMethod.java
private String formatParameter(Parameter param) {
	Annotation[] anns = param.getAnnotations();
	return (anns.length > 0 ?
			Arrays.stream(anns).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param :
			param.toString());
}
 
源代码14 项目: java-technology-stack   文件: ResolvableMethod.java
private String formatParameter(Parameter param) {
	Annotation[] anns = param.getAnnotations();
	return (anns.length > 0 ?
			Arrays.stream(anns).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param :
			param.toString());
}
 
源代码15 项目: java-technology-stack   文件: ResolvableMethod.java
private String formatParameter(Parameter param) {
	Annotation[] anns = param.getAnnotations();
	return (anns.length > 0 ?
			Arrays.stream(anns).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param :
			param.toString());
}
 
源代码16 项目: Geisha   文件: JettyServer.java
/**
 * 解析请求并返回响应
 */
private static void doResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String url = request.getRequestURI();
    RequestMethod requestMethod = RequestMethod.getEnum(request.getMethod());
    log.info("{} {}", requestMethod, url);
    MethodDetail methodDetail = UrlMappingPool.getInstance().getMap(url, requestMethod);

    // 如果找不到对应的匹配规则
    if (methodDetail == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.getWriter().print(Constants.NOT_FOUND);
        return;
    }

    Class clazz = methodDetail.getClazz();
    Object object = BeansPool.getInstance().getObject(clazz);
    if (object == null)
        throw new RuntimeException("can't find bean for " + clazz);

    Map<String, String> requestParam = new HashMap<>();
    request.getParameterMap().forEach((k, v) -> {
        requestParam.put(k, v[0]);
    });

    List<String> params = new ArrayList<>(); // 最终的方法参数
    Method method = methodDetail.getMethod();

    // 获取方法的所有的参数
    Parameter[] parameters = method.getParameters();
    for (Parameter parameter : parameters) {
        String name = null;
        // 获取参数上所有的注解
        Annotation[] annotations = parameter.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation.annotationType() == Param.class) {
                Param param = (Param) annotation;
                name = param.value();
                break;
            }
        }
        // 如果请求参数中存在这个参数就把该值赋给方法参数,否则赋值null
        params.add(requestParam.getOrDefault(name, null));
    }

    Object result = method.invoke(object, params.toArray());

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(result);
}
 
源代码17 项目: component-runtime   文件: ParameterModelService.java
public Param(final Parameter parameter) {
    this(parameter.getParameterizedType(), parameter.getAnnotations(), parameter.getName());
}
 
private ConstraintsModel constraintsFor( Method method,
                                         List<Class<?>> constraintClasses
                                       )
{
    List<ValueConstraintsModel> parameterConstraintModels = Collections.emptyList();

    Parameter[] parameters = method.getParameters();
    Type[] parameterTypes = method.getGenericParameterTypes();
    boolean constrained = false;
    for( int i = 0; i < parameters.length; i++ )
    {
        Parameter param = parameters[i];

        Annotation[] parameterAnnotation = param.getAnnotations();

        Name nameAnnotation = (Name) of( parameterAnnotation ).filter( isType( Name.class ) )
                                                              .findFirst().orElse( null );
        String name = nameAnnotation == null ? param.getName() : nameAnnotation.value();
        boolean optional = of( parameterAnnotation )
            .anyMatch( isType( Optional.class ) );
        ValueConstraintsModel parameterConstraintsModel = constraintsFor(
            Arrays.stream( parameterAnnotation ),
            parameterTypes[ i ],
            name,
            optional,
            constraintClasses,
            method );
        if( parameterConstraintsModel.isConstrained() )
        {
            constrained = true;
        }

        if( parameterConstraintModels.isEmpty() )
        {
            parameterConstraintModels = new ArrayList<>();
        }
        parameterConstraintModels.add( parameterConstraintsModel );
    }

    if( !constrained )
    {
        return new ConstraintsModel( Collections.emptyList() );
    }
    else
    {
        return new ConstraintsModel( parameterConstraintModels );
    }
}