java.lang.reflect.Parameter Java Examples
The following examples show how to use
java.lang.reflect.Parameter.
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: EndpointValidator.java From msf4j with Apache License 2.0 | 7 votes |
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 #2
Source File: AnnotationHelper.java From proteus with Apache License 2.0 | 6 votes |
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 #3
Source File: ComponentEventBusUtil.java From flow with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: MethodTest.java From j2objc with Apache License 2.0 | 6 votes |
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 #5
Source File: ComponentEventBusUtil.java From flow with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: BotControllerManager.java From lavaplayer with Apache License 2.0 | 6 votes |
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 #7
Source File: ControllerHandler.java From pippo with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: MethodCallDialog.java From blocktalk with GNU General Public License v3.0 | 6 votes |
@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 #9
Source File: SerDesMiddleware.java From enkan with Eclipse Public License 1.0 | 6 votes |
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 #10
Source File: GenericConstraintRule.java From BlogManagePlatform with Apache License 2.0 | 6 votes |
@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 #11
Source File: AnnotatedArgumentBuilder.java From graphql-spqr with Apache License 2.0 | 6 votes |
@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 #12
Source File: MethodParameter.java From java-technology-stack with MIT License | 6 votes |
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 #13
Source File: EndpointCommand.java From sshd-shell-spring-boot with Apache License 2.0 | 6 votes |
@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 #14
Source File: Methods.java From verifydata with Apache License 2.0 | 5 votes |
public static void addVerify(List<Verify> list, Method method, List<String> parmsType, List<String> parmsName, List<Object> verifyGroup) { // 校验组 verifyGroup.addAll(Arrays.asList(method.getAnnotationsByType(Validation.class)[0].value())); // 设置参数名 DefaultParameterNameDiscoverer defaultParameterNameDiscoverer = new DefaultParameterNameDiscoverer(); parmsName.addAll(Arrays.asList(defaultParameterNameDiscoverer.getParameterNames(method))); Parameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { parmsType.add(parameters[i].getType().getName()); if (parameters[i].isAnnotationPresent(Verify.class)) list.add(i, parameters[i].getAnnotationsByType(Verify.class)[0]); else list.add(null); } }
Example #15
Source File: StreamingLedgerSpecFactory.java From da-streamingledger with Apache License 2.0 | 5 votes |
@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 #16
Source File: CaptorParameterFactory.java From junit5-extensions with MIT License | 5 votes |
@Override public Object getParameterValue(Parameter parameter) { TypeToken<?> parameterType = TypeToken.of(parameter.getParameterizedType()); TypeToken<?> captorParameter = parameterType.resolveType(ArgumentCaptor.class.getTypeParameters()[0]); return ArgumentCaptor.forClass(captorParameter.getRawType()); }
Example #17
Source File: MockitoExtension.java From hypergraphql with Apache License 2.0 | 5 votes |
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 #18
Source File: ApiInvokeController.java From swagger-more with Apache License 2.0 | 5 votes |
private Map<String, Parameter> getParameterMap(List<String> names, Method method) { Map<String, Parameter> map = Maps.newLinkedHashMap(); if (names.isEmpty()) { Stream.of(method.getParameters()).forEach(parameter -> map.put(parameter.getName().replace("arg", "param"), parameter)); return map; } for (int i = 0; i < names.size(); i++) { map.put(names.get(i), method.getParameters()[i]); } return map; }
Example #19
Source File: TypeGeneratorUtils.java From panda with Apache License 2.0 | 5 votes |
static PandaPropertyParameter[] toParameters(TypeLoader typeLoader, Module module, Parameter[] parameters) { PandaPropertyParameter[] mappedParameters = new PandaPropertyParameter[parameters.length]; for (int index = 0; index < parameters.length; index++) { Parameter parameter = parameters[index]; Type type = TypeGeneratorManager.getInstance().getGenerator().findOrGenerate(typeLoader, module, parameter.getType()); mappedParameters[index] = new PandaPropertyParameter(index, type, parameter.getName(), parameter.isVarArgs(), false, false); } return mappedParameters; }
Example #20
Source File: AbstractMethodParameterParser.java From RestDoc with Apache License 2.0 | 5 votes |
@Override public ParameterModel parse(Parameter parameter, ParamJavadoc paramJavadoc, ParameterModel parameterModel) { parameterModel.setName(getParameterName(parameter)); if (paramJavadoc != null) { parameterModel.setDescription(FormatUtils.format(paramJavadoc.getComment())); } // 参数是Optional类型 Type actualParamType = parameter.getParameterizedType(); if (parameter.getType() == Optional.class) { if (parameter.getParameterizedType() instanceof ParameterizedType) { actualParamType = ((ParameterizedType)parameter.getParameterizedType()).getActualTypeArguments()[0]; } else { throw new RuntimeException("why?"); } } parameterModel.setParameterType(actualParamType); parameterModel.setLocation(getParameterLocation(parameter, actualParamType)); parameterModel = parseInternal(parameter, actualParamType, parameterModel); parameterModel.setRequired(isRequired(parameter, actualParamType)); if (actualParamType != parameter.getParameterizedType()) parameterModel.setRequired(false); return parameterModel; }
Example #21
Source File: StandardReflectionParameterNameDiscoverer.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public String[] getParameterNames(Constructor<?> ctor) { Parameter[] parameters = ctor.getParameters(); String[] parameterNames = new String[parameters.length]; for (int i = 0; i < parameters.length; i++) { Parameter param = parameters[i]; if (!param.isNamePresent()) { return null; } parameterNames[i] = param.getName(); } return parameterNames; }
Example #22
Source File: StubClass.java From baratine with GNU General Public License v2.0 | 5 votes |
private Parameter result(Parameter []params, Class<?> resultClass) { int paramLen = params.length; for (int i = 0; i < paramLen; i++) { if (resultClass.isAssignableFrom(params[i].getType())) { return params[i]; } } return null; }
Example #23
Source File: ParamSuffixGen.java From AsyncDao with MIT License | 5 votes |
@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 #24
Source File: BadClassFiles.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public void assertBadParameters(Class<?> cls) throws NoSuchMethodException { try { System.err.println("Trying " + cls); final Method method = cls.getMethod("m", int.class, int.class); final Parameter[] params = method.getParameters(); System.err.println("Name " + params[0].getName()); System.err.println("Did not see expected exception"); errors++; } catch(MalformedParametersException e) { System.err.println("Expected exception seen"); } }
Example #25
Source File: MethodParamNameUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenGetMethodParams_thenOk() throws NoSuchMethodException, SecurityException { List<Parameter> parameters = Arrays.asList( Person.class.getMethod("setFullName", String.class).getParameters()); Optional<Parameter> parameter = parameters.stream().filter(Parameter::isNamePresent).findFirst(); assertThat(parameter.get().getName()).isEqualTo("fullName"); }
Example #26
Source File: Describe.java From o2oa with GNU Affero General Public License v3.0 | 5 votes |
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; }
Example #27
Source File: DatasourceValidator.java From Poseidon with Apache License 2.0 | 5 votes |
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; }
Example #28
Source File: MockitoExtension.java From intellij-spring-assistant with MIT License | 5 votes |
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 #29
Source File: TypeUtil.java From fastquery with Apache License 2.0 | 5 votes |
/** * 查找出标识有注解的参数的具体值,没有找到返回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 File: OperationsTransformer.java From spring-openapi with MIT License | 5 votes |
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; }