Java Code Examples for java.lang.reflect.Parameter

The following examples show how to use java.lang.reflect.Parameter. 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: proteus   Source File: AnnotationHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static QueryParam createQueryParam(Parameter parameter)
{
    return new QueryParam()
    {
        @Override
        public String value()
        {
            QueryParam annotation = parameter.getAnnotation(QueryParam.class);

            if (annotation != null)
            {
                return annotation.value();
            }

            return parameter.getName();
        }
        @Override
        public Class<? extends Annotation> annotationType()
        {
            return QueryParam.class;
        }
    };
}
 
Example 2
Source Project: BlogManagePlatform   Source File: GenericConstraintRule.java    License: Apache License 2.0 6 votes vote down vote up
@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(), "或者其子类");
					}
				}
			}
		}
	}
}
 
Example 3
Source Project: flow   Source File: ComponentEventBusUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source Project: msf4j   Source File: EndpointValidator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean validateOnOpenMethod(Object webSocketEndpoint)
        throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
    EndpointDispatcher dispatcher = new EndpointDispatcher();
    Method method;
    if (dispatcher.getOnOpenMethod(webSocketEndpoint).isPresent()) {
        method = dispatcher.getOnOpenMethod(webSocketEndpoint).get();
    } else {
        return true;
    }
    validateReturnType(method);
    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 open message method: " +
                                                                    "string parameter without " +
                                                                    "@PathParam annotation.");
            }
        } else if (paraType != WebSocketConnection.class) {
            throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " +
                                                                paraType);
        }
    }
    return true;
}
 
Example 5
Source Project: sshd-shell-spring-boot   Source File: EndpointCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Autowired
EndpointCommand(ApplicationContext appCtx) {
    appCtx.getBeansWithAnnotation(Endpoint.class).entrySet().stream()
            .sorted(Comparator.comparing(e -> e.getKey()))
            .forEachOrdered(entry -> {
                log.debug("{} : {}", entry.getKey(), entry.getValue().getClass().getName());
                for (Method m : entry.getValue().getClass().getDeclaredMethods()) {
                    if (m.isAnnotationPresent(ReadOperation.class) || m.isAnnotationPresent(WriteOperation.class)) {
                        log.debug("\tOp: {}", m.getName());
                        for (Parameter p : m.getParameters()) {
                            log.debug("\t\tParameter {}, {}", p.getName(), p.getType().getName());
                        }
                    }
                }
            });
}
 
Example 6
Source Project: graphql-spqr   Source File: AnnotatedArgumentBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<OperationArgument> buildResolverArguments(ArgumentBuilderParams params) {
    Method resolverMethod = params.getResolverMethod();
    List<OperationArgument> operationArguments = new ArrayList<>(resolverMethod.getParameterCount());
    AnnotatedType[] parameterTypes = ClassUtils.getParameterTypes(resolverMethod, params.getDeclaringType());
    for (int i = 0; i < resolverMethod.getParameterCount(); i++) {
        Parameter parameter = resolverMethod.getParameters()[i];
        if (!params.getInclusionStrategy().includeArgument(parameter, params.getDeclaringType())) {
            continue;
        }
        AnnotatedType parameterType;
        try {
            parameterType = params.getTypeTransformer().transform(parameterTypes[i]);
        } catch (TypeMappingException e) {
            throw TypeMappingException.ambiguousParameterType(resolverMethod, parameter, e);
        }
        operationArguments.add(buildResolverArgument(parameter, parameterType, params));
    }
    return operationArguments;
}
 
Example 7
Source Project: blocktalk   Source File: MethodCallDialog.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == methodComboBox) {

        for (int i = 0; i < args.length; i++) {
            argTypes[i].setText("");
            args[i].setEnabled(false);
        }

        Method m = methodMap.get(methodComboBox.getSelectedItem());
        if (m == null)
            return;

        Parameter[] pars = m.getParameters();
        for (int i = 0; i < args.length && pars != null && i < pars.length; i++) {
            // FIXME find a way to show argument names
            argTypes[i].setText(pars[i].getType().getName()); // + " " + pars[i].getName());
            args[i].setEnabled(true);
        }
    }
}
 
Example 8
Source Project: flow   Source File: ComponentEventBusUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source Project: j2objc   Source File: MethodTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test_getParameters() throws Exception {
    Class[] expectedParameters = new Class[0];
    Method method = MethodTestHelper.class.getMethod("m1", expectedParameters);
    assertEquals(0, method.getParameters().length);

    expectedParameters = new Class[] { Object.class };
    method = MethodTestHelper.class.getMethod("m2", expectedParameters);

    // Test the information available via other Method methods. See ParameterTest and
    // annotations.ParameterTest for more in-depth Parameter testing.
    Parameter[] parameters = method.getParameters();
    assertEquals(1, parameters.length);
    assertEquals(Object.class, parameters[0].getType());

    // Check that corrupting our array doesn't affect other callers.
    parameters[0] = null;
    parameters = method.getParameters();
    assertEquals(1, parameters.length);
    assertEquals(Object.class, parameters[0].getType());
}
 
Example 10
Source Project: lavaplayer   Source File: BotControllerManager.java    License: Apache License 2.0 6 votes vote down vote up
private void registerControllerMethod(Class<?> controllerClass, Method method, BotCommandHandler annotation) {
  String commandName = annotation.name().isEmpty() ? method.getName().toLowerCase() : annotation.name();
  String usage = annotation.usage().isEmpty() ? null : annotation.usage();

  Parameter[] methodParameters = method.getParameters();
  if (methodParameters.length == 0 || !methodParameters[0].getType().isAssignableFrom(Message.class)) {
    return;
  }

  method.setAccessible(true);

  List<Class<?>> parameters = new ArrayList<>();
  for (int i = 1; i < methodParameters.length; i++) {
    parameters.add(methodParameters[i].getType());
  }

  Command command = new Command(commandName, usage, parameters, controllerClass, method);
  commands.put(command.name, command);
}
 
Example 11
Source Project: pippo   Source File: ControllerHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Init extractors from controller method.
 */
protected void initExtractors() {
    Parameter[] parameters = controllerMethod.getParameters();
    extractors = new MethodParameterExtractor[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        MethodParameter parameter = new MethodParameter(controllerMethod, i);
        MethodParameterExtractor extractor = application.getExtractors().stream()
            .filter(e -> e.isApplicable(parameter))
            .findFirst()
            .orElse(null);

        if (extractor == null) {
            throw new PippoRuntimeException(
                "Method '{}' parameter {} of type '{}' does not specify a extractor",
                LangUtils.toString(controllerMethod), i + 1, parameter.getParameterType());
        }

        extractors[i] = extractor;
    }
}
 
Example 12
Source Project: enkan   Source File: SerDesMiddleware.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void deserializeBody(Method method, HttpRequest request) throws IOException {
    String contentType = HttpRequestUtils.contentType(request);
    if (contentType == null) return;

    String[] mediaTypeTokens = contentType.split("/", 2);
    if (mediaTypeTokens.length == 2) {
        MediaType mediaType = new MediaType(mediaTypeTokens[0], mediaTypeTokens[1]);
        Parameter[] parameters = method != null ? method.getParameters() : new Parameter[0];
        BodyDeserializable bodyDeserializable = BodyDeserializable.class.cast(request);
        for (Parameter parameter : parameters) {
            Class<?> type = parameter.getType();
            Type genericType = parameter.getParameterizedType();

            if (parameterInjectors.stream().anyMatch(injector-> injector.isApplicable(type, request)))
                continue;

            Object body = deserialize(request, type, genericType, mediaType);
            bodyDeserializable.setDeserializedBody(body);
        }
        if (bodyDeserializable.getDeserializedBody() == null) {
            bodyDeserializable.setDeserializedBody(deserialize(request, Object.class, Object.class, mediaType));
        }
    }
}
 
Example 13
Source Project: java-technology-stack   Source File: MethodParameter.java    License: MIT License 6 votes vote down vote up
protected static int findParameterIndex(Parameter parameter) {
	Executable executable = parameter.getDeclaringExecutable();
	Parameter[] allParams = executable.getParameters();
	// Try first with identity checks for greater performance.
	for (int i = 0; i < allParams.length; i++) {
		if (parameter == allParams[i]) {
			return i;
		}
	}
	// Potentially try again with object equality checks in order to avoid race
	// conditions while invoking java.lang.reflect.Executable.getParameters().
	for (int i = 0; i < allParams.length; i++) {
		if (parameter.equals(allParams[i])) {
			return i;
		}
	}
	throw new IllegalArgumentException("Given parameter [" + parameter +
			"] does not match any parameter in the declaring executable");
}
 
Example 14
Source Project: selenium-jupiter   Source File: SeleniumExtension.java    License: Apache License 2.0 5 votes vote down vote up
private DriverHandler getDriverHandler(ExtensionContext extensionContext,
        Parameter parameter, Class<?> type, Class<?> constructorClass,
        Browser browser, boolean isRemote)
        throws InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    DriverHandler driverHandler = null;
    if (isRemote && browser != null) {
        driverHandler = (DriverHandler) constructorClass
                .getDeclaredConstructor(Parameter.class,
                        ExtensionContext.class, Config.class,
                        AnnotationsReader.class, Browser.class)
                .newInstance(parameter, extensionContext, getConfig(),
                        getAnnotationsReader(), browser);

    } else if (constructorClass.equals(OtherDriverHandler.class)
            && !browserListMap.isEmpty()) {
        driverHandler = (DriverHandler) constructorClass
                .getDeclaredConstructor(Parameter.class,
                        ExtensionContext.class, Config.class,
                        AnnotationsReader.class, Class.class)
                .newInstance(parameter, extensionContext, getConfig(),
                        getAnnotationsReader(), type);

    } else {
        driverHandler = (DriverHandler) constructorClass
                .getDeclaredConstructor(Parameter.class,
                        ExtensionContext.class, Config.class,
                        AnnotationsReader.class)
                .newInstance(parameter, extensionContext, getConfig(),
                        getAnnotationsReader());

    }
    return driverHandler;
}
 
Example 15
Source Project: fast-framework   Source File: HandlerInvoker.java    License: 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 16
/**
 * Given a parameter name annotated with either {@link ParameterName} or {@link JsonProperty},
 * returns the name of a corresponding getter
 * @param parameter The parameter
 * @return The name of a corresponding getter
 */
String getterNameFromParameter(Parameter parameter) {
    final String getterPrefix;
    if (parameter.getType() == Boolean.class || parameter.getType() == boolean.class) {
        getterPrefix = "is";
    } else {
        getterPrefix = "get";
    }
    return getterPrefix + toCamelCase(fetchParameterName(parameter));
}
 
Example 17
Source Project: camunda-bpm-swagger   Source File: ParameterRepository.java    License: Apache License 2.0 5 votes vote down vote up
public static Optional<Pair<Class<?>, String>> lookup(final Parameter param) {
  final Pair<Class<?>, String> pair = predefinedParameters.get(param.getType().getName());
  if (pair != null) {
    return Optional.of(pair);
  }
  return Optional.empty();
}
 
Example 18
Source Project: eclair   Source File: AnnotationExtractorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void hasAnyAnnotationDetectsParameterLogs() throws NoSuchMethodException {
    // given
    Method method = ClassWithAnnotatedMethods.class.getDeclaredMethod("parameterLogs", String.class);
    Parameter parameter = method.getParameters()[0];
    // when
    boolean has = annotationExtractor.hasAnyAnnotation(parameter);
    // then
    assertTrue(has);
}
 
Example 19
Source Project: rewrite   Source File: JavaType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Lazily built so that a {@link org.openrewrite.java.internal.grammar.JavaParser} operating over a set of code
 * has an opportunity to build {@link Class} instances for sources found in the repo that can provide richer information
 * for constructor parameter types.
 *
 * @return The set of public constructors for a class.
 */
public List<Method> getConstructors() {
    if (constructors != null) {
        return constructors;
    }

    synchronized (flyweights) {
        List<Method> reflectedConstructors = new ArrayList<>();
        try {
            java.lang.Class<?> reflectionClass = java.lang.Class.forName(fullyQualifiedName, false, JavaType.class.getClassLoader());
            for (Constructor<?> constructor : reflectionClass.getConstructors()) {
                ShallowClass selfType = new ShallowClass(fullyQualifiedName);

                // TODO can we generate a generic signature as well?
                Method.Signature resolvedSignature = new Method.Signature(selfType, Arrays.stream(constructor.getParameterTypes())
                        .map(pt -> Class.build(pt.getName()))
                        .collect(toList()));

                List<String> parameterNames = Arrays.stream(constructor.getParameters()).map(Parameter::getName).collect(toList());

                // Name each constructor "<reflection_constructor>" to intentionally disambiguate from method signatures parsed
                // by JavaParser, which may have richer information but which would only be available for types found in the source
                // repository.
                reflectedConstructors.add(Method.build(selfType, "<reflection_constructor>", resolvedSignature, resolvedSignature,
                        parameterNames, Set.of(Flag.Public)));
            }
        } catch (ClassNotFoundException ignored) {
            // oh well, we tried
        }
        return reflectedConstructors;
    }
}
 
Example 20
Source Project: baratine   Source File: StubClass.java    License: GNU General Public License v2.0 5 votes vote down vote up
private MethodAmp createPin(MethodAmp delegate,
                            Parameter result)
{
  Class<?> api = TypeRef.of(result.getParameterizedType())
                        .to(ResultChain.class)
                        .param(0)
                        .rawClass();
  
  return new MethodStubResultPin(delegate, api);
}
 
Example 21
Source Project: joyrpc   Source File: HttpToJoyHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 解析参数
 *
 * @param invocation 请求
 * @param message    消息
 * @param parametric 参数化
 * @param url        url
 * @param params     参数名
 * @return 参数值对象
 */
protected Object[] parseArgs(final Invocation invocation,
                             final HttpRequestMessage message,
                             final Parametric parametric,
                             final URL url,
                             final List<String> params) throws IOException {
    Method method = invocation.getMethod();
    Parameter[] parameters = method.getParameters();
    if (parameters.length == 0) {
        return new Object[0];
    }
    Object[] args;
    //判断是否有参数名称
    boolean hasName = parameters[0].isNamePresent();
    HttpMethod reqMethod = message.getHttpMethod();
    if (reqMethod != HttpMethod.GET) {
        //获取压缩
        Compression compression = getCompression(parametric, HttpHeaders.Names.CONTENT_ENCODING);
        //解压缩
        byte[] content = decompress(compression, message.content());
        //构造泛化调用参数
        invocation.setArgs(new Object[]{invocation.getMethodName(), null, new Object[]{content}});
        //反序列化
        args = defSerializer.deserialize(invocation);
    } else if (params.size() < parameters.length) {
        throw new CodecException("The number of parameter is wrong.");
    } else {
        args = new Object[parameters.length];
        //和老版本兼容,历史原因问题,可能请求的参数和名称不一致,只有一致的情况下才按照名称获取
        boolean match = hasName && isMatch(params, parameters);
        String name;
        Parameter parameter;
        for (int i = 0; i < parameters.length; i++) {
            parameter = parameters[i];
            name = match ? parameter.getName() : params.get(i);
            args[i] = binding.convert(invocation.getClass(), method, parameter, i, url.getString(name));
        }
    }
    return args;
}
 
Example 22
Source Project: typescript-generator   Source File: JsonbParser.java    License: MIT License 5 votes vote down vote up
private Stream<PropertyModel> visitConstructor(final Constructor<?> constructor) {
    // JSON-B 1.0 assumes all constructor params are required even if impls can diverge on that due
    // to user feedbacks so for our libraryDefinition let's assume it is true.
    // only exception is about optional wrappers which can be optional indeed
    final List<Type> parameterTypes = settings.getTypeParser().getConstructorParameterTypes(constructor);
    final List<Pair<Parameter, Type>> parameters = Utils.zip(Arrays.asList(constructor.getParameters()), parameterTypes);
    return parameters.stream()
            .map(it -> {
                final Type type = it.getValue2();
                final Parameter parameter = it.getValue1();
                final Optional<JsonbProperty> property = Optional.ofNullable(
                        parameter.getAnnotation(JsonbProperty.class));
                final PropertyMember propertyMember = new PropertyMember(
                        parameter, it.getValue2(), parameter.getAnnotatedType(), parameter::getAnnotation);
                return JsonbParser.this.processTypeAndCreateProperty(
                        property
                            .map(JsonbProperty::value)
                            .filter(p -> !p.isEmpty())
                            .orElseGet(parameter::getName),
                        type, null,
                        settings.optionalProperties != OptionalProperties.useLibraryDefinition ?
                                isPropertyOptional(propertyMember) :
                                (isOptional(type) || OptionalInt.class == type ||
                                OptionalLong.class == type || OptionalDouble.class == type ||
                                property.map(JsonbProperty::nillable).orElse(false)),
                        constructor.getDeclaringClass(), new ParameterMember(parameter),
                        null, null);
            });
}
 
Example 23
Source Project: oxygen   Source File: OthersParamBinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataBinder build(Parameter parameter) {
  DataBinder dataBinder = new DataBinder();
  dataBinder.setType(parameter.getType());
  dataBinder.setName(parameter.getName());
  dataBinder.setFunc(ctx -> {
    if (RoutingContext.class.isAssignableFrom(parameter.getType())) {
      return ctx;
    }
    return null;
  });
  return dataBinder;
}
 
Example 24
/**
 * Formats the given parameters and arguments to a comma-separated list of {@code $parameterName=$argumentName}.
 * Arguments {@link String} representation are therefore treated specially.
 *
 * @param parameters used to for formatting
 * @param arguments to be formatted
 * @return the formatted {@link String} of the given {@link Parameter}{@code []} and {@link List}{@code <Object>}
 */
protected String formatAll(Parameter[] parameters, List<Object> arguments) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int idx = 0; idx < arguments.size(); idx++) {
        String parameterName = (parameters.length > idx) ? parameters[idx].getName() : "?";
        Object argument = arguments.get(idx);

        stringBuilder.append(parameterName).append("=").append(format(argument));
        if (idx < arguments.size() - 1) {
            stringBuilder.append(", ");
        }
    }
    return stringBuilder.toString();
}
 
Example 25
Source Project: AsyncDao   Source File: ParamSuffixGen.java    License: MIT License 5 votes vote down vote up
@Override
public SqlNode generateSql() {
    SqlNode orderNode = generateOrder();
    Optional<Parameter> limit = Arrays.asList(method.getParameters()).stream()
            .filter(parameter -> parameter.isAnnotationPresent(Limit.class))
            .findFirst();

    Optional<Parameter> offset = Arrays.asList(method.getParameters()).stream()
            .filter(parameter -> parameter.isAnnotationPresent(OffSet.class))
            .findFirst();

    StringBuilder stringBuilder = new StringBuilder();
    if (offset.isPresent() || offset.isPresent()) {
        stringBuilder.append(" limit ");
    }
    offset.ifPresent(parameter -> {
        stringBuilder.append("#{");
        stringBuilder.append(parameter.getName());
        stringBuilder.append("},");
    });

    limit.ifPresent(parameter -> {
        stringBuilder.append("#{");
        stringBuilder.append(parameter.getName());
        stringBuilder.append("}");
    });

    return new MixedSqlNode(Arrays.asList(orderNode, new StaticTextSqlNode(stringBuilder.toString())));
}
 
Example 26
Source Project: intellij-spring-assistant   Source File: MockitoExtension.java    License: MIT License 5 votes vote down vote up
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
  Class<?> mockType = parameter.getType();
  Store mocks = extensionContext.getStore(Namespace.create(MockitoExtension.class, mockType));
  String mockName = getMockName(parameter);

  if (mockName != null) {
    return mocks.getOrComputeIfAbsent(mockName, key -> mock(mockType, mockName));
  } else {
    return mocks.getOrComputeIfAbsent(mockType.getCanonicalName(), key -> mock(mockType));
  }
}
 
Example 27
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean isOfGenericType(Parameter parameter, Class<?> baseType, TypeInformation<?> type) {
    if (!(parameter.getParameterizedType() instanceof ParameterizedType)) {
        return false;
    }
    ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
    if (parameterizedType.getRawType() != baseType) {
        return false;
    }
    Type t = parameterizedType.getActualTypeArguments()[0];
    return t == type.getTypeClass();
}
 
Example 28
Source Project: spring-openapi   Source File: OperationsTransformer.java    License: MIT License 5 votes vote down vote up
private Class<?> getGenericParam(Parameter parameter) {
	if (parameter.getParameterizedType() instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
		if (isNotEmpty(parameterizedType.getActualTypeArguments())) {
			return (Class<?>) parameterizedType.getActualTypeArguments()[0];
		}
	}
	return null;
}
 
Example 29
Source Project: fastquery   Source File: TypeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查找出标识有注解的参数的具体值,没有找到返回null
 *
 * @param clazz      注解class
 * @param parameters 方法的参数类型列表
 * @param args       该方的具体参数
 * @return 值
 */
public static Object findAnnotationParameterVal(Class<? extends Annotation> clazz, Parameter[] parameters, Object... args) {
    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i].getAnnotation(clazz) != null) {
            return args[i];
        }
    }
    return null;
}
 
Example 30
Source Project: Poseidon   Source File: DatasourceValidator.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> validate(Class<? extends DataSource<?>> dsClass) {
    final ArrayList<String> errors = new ArrayList<>();
    int injectableConstructorCount = 0;
    final Constructor<?>[] declaredConstructors = dsClass.getDeclaredConstructors();
    for (Constructor<?> constructor : declaredConstructors) {
        if (constructor.getParameterCount() == 2) {
            continue;
        }

        if (!constructor.isAnnotationPresent(Inject.class)) {
            errors.add("Injectable constructor" + constructor.toGenericString() + "not annotated with @Inject");
            continue;
        }

        injectableConstructorCount++;
        final Parameter[] parameters = constructor.getParameters();
        final Set<String> datasourceRequestAttributes = new HashSet<>();
        for (Parameter parameter : parameters) {
            final RequestAttribute requestAttribute = parameter.getAnnotation(RequestAttribute.class);
            if (requestAttribute != null) {
                final String attribute = Optional.of(requestAttribute.value()).filter(StringUtils::isNotEmpty).orElse(parameter.getName());
                final boolean added = datasourceRequestAttributes.add(attribute);
                if (!added) {
                    errors.add("RequestAttribute: " + braced(attribute) + " is used twice");
                }
            }
        }
    }

    if (injectableConstructorCount > 1) {
        errors.add("More than 1 injectable constructor defined");
    }

    return errors;
}