Java Code Examples for java.lang.reflect.Parameter#isAnnotationPresent()

The following examples show how to use java.lang.reflect.Parameter#isAnnotationPresent() . 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 File: GenContext.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean checkIgnore(Parameter parameter) {
    Class<?> paramRawClz = parameter.getType();
    for (Class<?> clz : ignoreParamClasses) {
        if (clz.isAssignableFrom(paramRawClz)) {
            return true;
        }
    }

    for (Class<? extends Annotation> annoClz : ignoreParamAnnoClasses) {
        if (parameter.isAnnotationPresent(annoClz)) {
            return true;
        }
    }

    return false;
}
 
Example 2
Source File: EndpointDispatcher.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * Extract OnMessage method for String from the endpoint if exists.
 *
 * @param webSocketEndpoint Endpoint to extract method.
 * @return method optional to handle String messages.
 */
public Optional<Method> getOnStringMessageMethod(Object webSocketEndpoint) {
    Method[] methods = webSocketEndpoint.getClass().getMethods();
    Method returnMethod = null;
    for (Method method : methods) {
        if (method.isAnnotationPresent(OnMessage.class)) {
            Parameter[] parameters = method.getParameters();
            for (Parameter parameter: parameters) {
                if (!parameter.isAnnotationPresent(PathParam.class) &&
                        parameter.getType() == String.class) {
                    returnMethod = method;
                }

            }
        }
    }
    return Optional.ofNullable(returnMethod);
}
 
Example 3
Source File: AnnotatedArgumentBuilder.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
protected OperationArgument buildResolverArgument(Parameter parameter, AnnotatedType parameterType, ArgumentBuilderParams builderParams) {
    return new OperationArgument(
            parameterType,
            getArgumentName(parameter, parameterType, builderParams),
            getArgumentDescription(parameter, parameterType, builderParams.getEnvironment().messageBundle),
            defaultValue(parameter, parameterType, builderParams.getEnvironment()),
            parameter,
            parameter.isAnnotationPresent(GraphQLContext.class),
            builderParams.getInclusionStrategy().includeArgumentForMapping(parameter, parameterType, builderParams.getDeclaringType())
    );
}
 
Example 4
Source File: ConstructorStream.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Constructor<?> constructor) {

  if (constructor == null) {
    return false;
  }
  for (Parameter parameter : constructor.getParameters()) {
    if (!parameter.isAnnotationPresent(annotationType)) {
      return false;
    }
  }
  return true;
}
 
Example 5
Source File: Methods.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Method method) {

  if (method == null) {
    return false;
  }
  for (Parameter parameter : method.getParameters()) {
    if (!parameter.isAnnotationPresent(annotationType)) {
      return false;
    }
  }
  return true;
}
 
Example 6
Source File: ShiroAuthorizingParamInterceptor.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private static Iterable<JobKeyGetter> annotatedParameterGetters(Method method) {
  for (Method candidateMethod : getCandidateMethods(method)) {
    Parameter[] parameters = candidateMethod.getParameters();
    ImmutableList.Builder<JobKeyGetter> jobKeyGetters = ImmutableList.builder();
    for (int i = 0; i < parameters.length; i++) {
      Parameter param = parameters[i];
      if (param.isAnnotationPresent(AuthorizingParam.class)) {
        Class<?> parameterType = param.getType();
        @SuppressWarnings("unchecked")
        Optional<Function<Object, Optional<JobKey>>> jobKeyGetter =
            Optional.ofNullable(
                (Function<Object, Optional<JobKey>>) FIELD_GETTERS_BY_TYPE.get(parameterType));
        if (!jobKeyGetter.isPresent()) {
          throw new UnsupportedOperationException(
              "No "
                  + JobKey.class.getName()
                  + " field getter was supplied for "
                  + parameterType.getName());
        }

        jobKeyGetters.add(new JobKeyGetter(i, jobKeyGetter.get()));
      }
    }

    ImmutableList<JobKeyGetter> getters = jobKeyGetters.build();
    if (!Iterables.isEmpty(getters)) {
      return getters;
    }
  }

  throw new UnsupportedOperationException(
      "No parameter annotated with "
          + AuthorizingParam.class.getName()
          + " found on method "
          + method.getName()
          + " of "
          + method.getDeclaringClass().getName()
          + " or any of its superclasses.");
}
 
Example 7
Source File: HandlerInvoker.java    From fast-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 请求处理器
 * 根据请求,获取请求参数
 * 调用Method,获取返回值
 * 调用View,返回响应
 *
 * @param request
 * @param response
 * @param handler
 */
public static void invokeHandler(HttpServletRequest request, HttpServletResponse response, HandlerBody handler) {
    List<Object> controllerMethodParamList = new ArrayList<>();
    Method controllerMethod = handler.getControllerMethod();

    // POST 请求
    if (request.getMethod().equals(RequestMethod.POST.toString())) {
        List<Class<?>> getParameterTypes = new ArrayList();
        Class<?> postParamType = null;

        for (Parameter p : controllerMethod.getParameters()) {
            if (p.isAnnotationPresent(PostParam.class)) {
                postParamType = p.getType();
            } else {
                getParameterTypes.add(p.getType());
            }
        }
        controllerMethodParamList = WebUtil.getRequestParamMap(request, getParameterTypes.toArray(new Class<?>[0]));
        Object postParamObject = WebUtil.getRequestBody(request, postParamType);
        controllerMethodParamList.add(0, postParamObject);

    }
    // GET 请求
    else if (request.getMethod().equals(RequestMethod.GET.toString())) {
        // 从 Request 获取参数 - Controller.Method 的 ParamList
        controllerMethodParamList = WebUtil.getRequestParamMap(request, controllerMethod.getParameterTypes());
    }

    // ReflectUtil 获取 Controller.Method 的返回值
    Object controllerMethodResult = ReflectUtil.invokeControllerMethod(handler.getControllerClass(),
        handler.getControllerMethod(), controllerMethodParamList);

    // View 处理
    ViewResolver.resolveView(request, response, controllerMethodResult, handler);
}
 
Example 8
Source File: InternationalizationServiceFactory.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private Function<Object[], Locale> createLocaleExtractor(final Method method) {
    Parameter[] parameters = method.getParameters();
    for (int i = 0; i < method.getParameterCount(); i++) {
        Parameter p = parameters[i];
        if (p.isAnnotationPresent(Language.class)) {
            final int idx = i;
            if (String.class == p.getType()) {
                return params -> new Locale(ofNullable(params[idx]).map(String::valueOf).orElse("en"));
            }
            return params -> Locale.class.cast(params[idx]);
        }
    }
    return p -> localeSupplier.get();
}
 
Example 9
Source File: ProcessorImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private BiFunction<InputFactory, OutputFactory, Object> buildProcessParamBuilder(final Parameter parameter) {
    if (parameter.isAnnotationPresent(Output.class)) {
        return (inputs, outputs) -> {
            final String name = parameter.getAnnotation(Output.class).value();
            return outputs.create(name);
        };
    }

    final Class<?> parameterType = parameter.getType();
    final String inputName =
            ofNullable(parameter.getAnnotation(Input.class)).map(Input::value).orElse(Branches.DEFAULT_BRANCH);
    return (inputs, outputs) -> doConvertInput(parameterType, inputs.read(inputName));
}
 
Example 10
Source File: ValueSourceAnnotatedMethod.java    From bazel with Apache License 2.0 5 votes vote down vote up
ImmutableMap<Parameter, Object> getResolvableParameters() {
  String[] providedParamValues = parameterValueSource.value();
  int i = 0;
  ImmutableMap.Builder<Parameter, Object> resolvableParameterValues = ImmutableMap.builder();
  for (Parameter parameter : getMethod().getParameters()) {
    if (parameter.isAnnotationPresent(FromParameterValueSource.class)) {
      resolvableParameterValues.put(
          parameter, parsePrimitive(providedParamValues[i++], parameter.getType()));
    }
  }
  return resolvableParameterValues.build();
}
 
Example 11
Source File: NativeQueryInfo.java    From spring-native-query with MIT License 5 votes vote down vote up
public static void setParameters(NativeQueryInfo info, MethodInvocation invocation) {
    info.sql = null;
    info.sort = null;
    info.parameterList = new ArrayList<>();
    info.pageable = null;
    for (int i = 0; i < invocation.getArguments().length; i++) {
        Object argument = invocation.getArguments()[i];
        Parameter parameter = invocation.getMethod().getParameters()[i];
        if (parameter.getType().isAssignableFrom(Pageable.class)) {
            info.pageable = (Pageable) argument;
            if (info.sort == null) {
                info.sort = info.pageable.getSort();
            }
        } else if (parameter.getType().isAssignableFrom(Sort.class)) {
            info.sort = (Sort) argument;
        } else {
            if (parameter.isAnnotationPresent(NativeQueryParam.class)) {
                NativeQueryParam param = parameter.getAnnotation(NativeQueryParam.class);
                if (param.addChildren()) {
                    info.parameterList.addAll(NativeQueryParameter.ofDeclaredMethods(param.value(), parameter.getType(), argument));
                } else {
                    if (argument instanceof Map) {
                        info.parameterList.addAll(NativeQueryParameter.ofMap((Map) argument, param.value()));
                    } else {
                        info.parameterList.add(new NativeQueryParameter(param.value(), param.operator().getTransformParam().apply(argument)));
                    }
                }
            } else {
                if (argument instanceof Map) {
                    info.parameterList.addAll(NativeQueryParameter.ofMap((Map) argument, parameter.getName()));
                } else {
                    info.parameterList.add(new NativeQueryParameter(parameter.getName(), argument));
                }
            }
        }
    }
}
 
Example 12
Source File: ProcessorFlowsFactory.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private boolean isInput(final Parameter p) {
    return p.isAnnotationPresent(Input.class) || !p.isAnnotationPresent(Output.class);
}
 
Example 13
Source File: ParameterArgs.java    From concursus with MIT License 4 votes vote down vote up
private static String getParameterName(Parameter parameter) {
    return parameter.isAnnotationPresent(Name.class)
            ? parameter.getAnnotation(Name.class).value()
            : parameter.getName();
}
 
Example 14
Source File: ApiClientMethod.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public ApiClientMethodParameter(Method method, Parameter parameter, int parameterIndex) {
	super(method, parameter, parameterIndex);
	this.injectProperties = parameter.isAnnotationPresent(InjectProperties.class);
}
 
Example 15
Source File: ModuleOverrideHandler.java    From Wizardry with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns a list of override methods from a given type, implementing them.
 *
 * @param clazz      the type.
 * @param hasContext if <code>true</code> then the method may contain context parameters.
 * @return a collection, mapping override names to their according methods.
 * @throws ModuleInitException if a method exists having invalid argument types or if some issues with reflection occurred.
 */
static HashMap<String, OverrideMethod> getOverrideMethodsFromClass(Class<?> clazz, boolean hasContext) throws ModuleInitException {
	HashMap<String, OverrideMethod> overridableMethods = new HashMap<>();
	// Determine overriden methods via reflection
	// FIXME: Separation of concerns: Overridable methods are not part of factory. Move them or rename factory class appropriately.
	for (Method method : clazz.getMethods()) {
		ModuleOverride ovrd = method.getDeclaredAnnotation(ModuleOverride.class);
		if (ovrd == null)
			continue;

		if (overridableMethods.containsKey(ovrd.value()))
			throw new ModuleInitException("Multiple methods exist in class '" + clazz + "' with same override name '" + ovrd.value() + "'.");

		try {
			method.setAccessible(true);
		} catch (SecurityException e) {
			throw new ModuleInitException("Failed to aquire reflection access to method '" + method.toString() + "', annotated by @ModuleOverride.", e);
		}

		// Search for context parameters
		int idxContextParamRing = -1;
		int idxContextParamSuper = -2;
		Parameter[] params = method.getParameters();
		for (int i = 0; i < params.length; i++) {
			Parameter param = params[i];
			if (param.isAnnotationPresent(ContextRing.class)) {
				if (idxContextParamRing >= 0)
					throw new ModuleInitException("Method '" + method.toString() + "' has invalid @ContextRing annotated parameter. It is not allowed on multiple parameters.");
				idxContextParamRing = i;
			}
			if (param.isAnnotationPresent(ContextSuper.class)) {
				if (idxContextParamSuper >= 0)
					throw new ModuleInitException("Method '" + method.toString() + "' has invalid @ContextSuper annotated parameter. It is not allowed on multiple parameters.");
				idxContextParamSuper = i;
			}
		}

		if (!hasContext) {
			if (idxContextParamRing >= 0 || idxContextParamSuper >= 0)
				throw new ModuleInitException("Context parameters are not allowed.");
		}

		if (idxContextParamRing == idxContextParamSuper)
			throw new ModuleInitException("Method '" + method.toString() + "' has a parameter which is annotated with multiple roles.");

		OverrideMethod ovrdMethod = new OverrideMethod(method, idxContextParamRing, idxContextParamSuper);
		overridableMethods.put(ovrd.value(), ovrdMethod);
	}

	return overridableMethods;
}
 
Example 16
Source File: DirectiveValueDeserializer.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(AnnotatedType type, Parameter parameter) {
    return parameter != null && parameter.isAnnotationPresent(GraphQLDirective.class);
}
 
Example 17
Source File: BasicParamBinder.java    From oxygen with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supported(Parameter parameter) {
  return parameter.isAnnotationPresent(Param.class);
}
 
Example 18
Source File: ContextInjector.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(AnnotatedType type, Parameter parameter) {
    return parameter != null && parameter.isAnnotationPresent(GraphQLContext.class);
}
 
Example 19
Source File: CookieParamBinder.java    From oxygen with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supported(Parameter parameter) {
  return parameter.isAnnotationPresent(CookieParam.class);
}
 
Example 20
Source File: ModuleOverrideHandler.java    From Wizardry with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Returns whether a parameter is a special one, taking values from the given caller context.
 *
 * @param param the parameter.
 * @return <code>true</code> iff yes.
 */
private static boolean isExtraParameter(Parameter param) {
	return param.isAnnotationPresent(ContextRing.class) ||
			param.isAnnotationPresent(ContextSuper.class);
}