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

The following examples show how to use java.lang.reflect.Parameter#getType() . 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 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 2
Source File: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
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);
	}
}
 
Example 3
Source File: LocalVariableAssembler.java    From spring-boot-netty with MIT License 6 votes vote down vote up
static void assembleLocalVariables(final MethodVisitor m, final Label ms, final Label me,
                                          final String invokerDescriptor, final Parameter[] invokeParameters,
                                          final Parameter[] targetMethodParameters, final boolean sendResult) {

    final int resultIdx = getResultIdx(invokeParameters);
    final int firstVarIdx = getFirstVarIdx(invokeParameters, sendResult);
    m.visitLocalVariable("this", invokerDescriptor, null, ms, me, 0);

    for (int i = 0; i < invokeParameters.length; i++) {
        final Parameter parameter = invokeParameters[i];
        final Class<?> parameterType = parameter.getType();
        final String descriptor = Type.getDescriptor(parameterType);

        //noinspection StringConcatenationMissingWhitespace
        m.visitLocalVariable("arg" + i, descriptor, null, ms, me, i + 1);
    }

    if (sendResult) {
        m.visitLocalVariable("result", OBJ_DESCRIPTOR, null, ms, me, resultIdx);
    }

    for (int i = 0; i < targetMethodParameters.length; i++) {
        //noinspection StringConcatenationMissingWhitespace
        m.visitLocalVariable("o" + i, OBJ_DESCRIPTOR, null, ms, me, i + firstVarIdx);
    }
}
 
Example 4
Source File: MockitoExtension.java    From sonar-gerrit-plugin with Apache License 2.0 6 votes vote down vote up
private Object getMock(
    Parameter parameter, ExtensionContext extensionContext) {

    Class<?> mockType = parameter.getType();
    ExtensionContext.Store mocks = extensionContext.getStore(ExtensionContext.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 5
Source File: InjectorProcessor.java    From panda with Apache License 2.0 6 votes vote down vote up
protected InjectorResourceBind<Annotation>[] fetchBinds(Annotation[] annotations, Executable executable) {
    InjectorResources resources = injector.getResources();
    Parameter[] parameters = executable.getParameters();
    InjectorResourceBind<Annotation>[] binds = ObjectUtils.cast(new InjectorResourceBind[parameters.length]);

    for (int index = 0; index < annotations.length; index++) {
        Annotation annotation = annotations[index];
        Parameter parameter = parameters[index];

        Class<?> requiredType = annotation != null ? annotation.annotationType() : parameter.getType();
        Option<InjectorResourceBind<Annotation>> bindValue = resources.getBind(requiredType);

        binds[index] = bindValue.getOrElseThrow(() -> {
            throw new DependencyInjectionException("Missing bind for " + parameter + " parameter");
        });
    }

    return binds;
}
 
Example 6
Source File: JunitServerExtension.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
	final Parameter parameter = parameterContext.getParameter();
	final Class<?> parameterClass = parameter.getType();
	final EmbeddedServerRunner serverAdapter = findEmbeddedServerAdapterInStore(extensionContext);

	// Fast case: a perfect match.
	if (RESOLVERS.containsKey(parameterClass)) {
		return RESOLVERS.get(parameterClass).resolve(parameterContext, serverAdapter);
	}

	for (Class<?> klass : RESOLVERS.keySet()) {
		if (klass.isAssignableFrom(parameterClass)) {
			return RESOLVERS.get(klass).resolve(parameterContext, serverAdapter);
		}
	}

	// Should not happen since Junit framework will call this method if, and only if, the
	// method `supportsParameter` has previously returned `true`.
	return null;
}
 
Example 7
Source File: EndpointValidator.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private boolean validateOnCloseMethod(Object webSocketEndpoint)
        throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
    EndpointDispatcher dispatcher = new EndpointDispatcher();
    Method method;
    if (dispatcher.getOnCloseMethod(webSocketEndpoint).isPresent()) {
        method = dispatcher.getOnCloseMethod(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 close message method: " +
                                                                    "string parameter without " +
                                                                    "@PathParam annotation.");
            }
        } else if (paraType != CloseReason.class && paraType != WebSocketConnection.class) {
            throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " +
                                                                paraType);
        }
    }
    return true;
}
 
Example 8
Source File: AsyncTestRunner.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static Class<?> getCallbackType(Class<?> promiseLike, Parameter parameter)
    throws InvalidTypeException {
  if (!isValidCallbackType(parameter.getType())) {
    throw new InvalidTypeException(
        ErrorMessage.INVALID_CALLBACK_PARAMETER.format(
            promiseLike.getCanonicalName(), parameter.getName()));
  }
  return parameter.getType();
}
 
Example 9
Source File: DataEventMessageDispatcher.java    From koper with Apache License 2.0 5 votes vote down vote up
/**
 * 获得方法调用时的参数 (参数绑定)
 *
 * @param method    具体事件方法
 * @param dataEvent 事件上下文信息
 * @return 该方法的所有参数(返回是一个Object[])
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private Object[] getDataEventMethodParameters(Method method, DataEvent dataEvent)
        throws InstantiationException, IllegalAccessException {

    final List<?> args = dataEvent.getArgs();
    final int length = method.getParameters().length;

    Object[] parameters = new Object[length];
    for (int i = 0; i < length; i++) {
        final Parameter parameter = method.getParameters()[i];

        final Class<?> parameterTypeClass = parameter.getType();

        Object o1;
        // 如果角标大小等于args的大小, 说明最后一位是 DataEvent
        if (i == args.size()) {
            o1 = dataEvent;
        } else {
            Object o = args.get(i);

            if (parameterTypeClass.getName().equals(DataEvent.class.getName())) {
                o1 = dataEvent;
            } else {
                o1 = ConverterCenter.convertValue(parameterTypeClass, o);
            }
        }
        parameters[i] = o1;
    }
    return parameters;
}
 
Example 10
Source File: MockitoExtension.java    From hypergraphql with Apache License 2.0 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 11
Source File: MockitoExtension.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private Object getMock(Parameter parameter, ExtensionContext extensionContext) {
    Class<?> mockType = parameter.getType();
    ExtensionContext.Store mocks = extensionContext.getStore(ExtensionContext.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 12
Source File: SpannerStatementQueryExecutor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void bindParameter(ValueBinder<Statement.Builder> bind,
		Function<Object, Struct> paramStructConvertFunc, SpannerCustomConverter spannerCustomConverter,
		Object originalParam, Parameter paramMetadata) {

	// Gets the type of the bind parameter; if null then infer the type from the parameter metadata.
	Class propType = originalParam != null ? originalParam.getClass() : paramMetadata.getType();
	if (ConversionUtils.isIterableNonByteArrayType(propType)) {
		if (!ConverterAwareMappingSpannerEntityWriter.attemptSetIterableValueOnBinder((Iterable) originalParam,
				bind, spannerCustomConverter, (Class) ((ParameterizedType) paramMetadata.getParameterizedType())
						.getActualTypeArguments()[0])) {
			throw new IllegalArgumentException(
					"Could not convert to an ARRAY of compatible type: " + paramMetadata);
		}
		return;
	}
	if (!ConverterAwareMappingSpannerEntityWriter.attemptBindSingleValue(originalParam, propType,
			bind, spannerCustomConverter)) {
		if (paramStructConvertFunc == null) {
			throw new IllegalArgumentException("Param: " + originalParam
					+ " is not a supported type: " + propType);
		}
		try {
			Object unused = ((BiFunction<ValueBinder, Object, Struct>)
					ConverterAwareMappingSpannerEntityWriter.singleItemTypeValueBinderMethodMap
					.get(Struct.class)).apply(bind, paramStructConvertFunc.apply(originalParam));
		}
		catch (SpannerDataException ex) {
			throw new IllegalArgumentException("Param: " + originalParam
					+ " is not a supported type: " + propType, ex);
		}
	}
}
 
Example 13
Source File: HttpToJoyHandler.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
/**
 * 把字符串转换成参数类型
 *
 * @param clazz     类型
 * @param method    方法
 * @param parameter 参数类型
 * @param index     参数索引
 * @param value     字符串
 * @return
 */
protected Object convert(final Class<?> clazz, final Method method, final Parameter parameter, final int index, final String value) {
    Class<?> type = parameter.getType();
    if (String.class.equals(type)) {
        try {
            return URLDecoder.decode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    } else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
        return Boolean.parseBoolean(value);
    } else if (byte.class.equals(type) || Byte.class.equals(type)) {
        return Byte.decode(value);
    } else if (short.class.equals(type) || Short.class.equals(type)) {
        return Short.decode(value);
    } else if (char.class.equals(type) || Character.class.equals(type)) {
        return value.charAt(0);
    } else if (int.class.equals(type) || Integer.class.equals(type)) {
        return Integer.decode(value);
    } else if (long.class.equals(type) || Long.class.equals(type)) {
        return Long.decode(value);
    } else if (float.class.equals(type) || Float.class.equals(type)) {
        return Float.valueOf(value);
    } else if (double.class.equals(type) || Double.class.equals(type)) {
        return Double.valueOf(value);
    } else {
        throw new UnsupportedOperationException();
    }
}
 
Example 14
Source File: CdiParameterResolverFactory.java    From cdi with Apache License 2.0 5 votes vote down vote up
@Override
public ParameterResolver<?> createInstance(final Executable executable,
        final Parameter[] parameters, final int parameterIndex) {
    final Parameter parameter = parameters[parameterIndex];

    if (this.beanManager == null) {
        logger.error(
                "BeanManager was null. This is a fatal error, an instance of {} {} is not created.",
                parameter.getType(),
                parameter.getAnnotations());
        return null;
    }

    logger.trace("Create instance for {} {}.", parameter.getType(), 
            parameter.getAnnotations());
    
    final Set<Bean<?>> beansFound = beanManager.getBeans(parameter.getType(), 
            parameter.getAnnotations());
    
    if (beansFound.isEmpty()) {
        return null;
    } else if (beansFound.size() > 1) {
        if (logger.isWarnEnabled()) {
            logger.warn("Ambiguous reference for parameter type {} with qualifiers {}.", 
                    parameter.getType().getName(), parameter.getAnnotations());
        }
        
        return null;
    } else {
        return new CdiParameterResolver(beanManager, 
                beansFound.iterator().next(), parameter.getType());
    }
}
 
Example 15
Source File: MockitoExtension.java    From intellij-spring-assistant with 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 16
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 17
Source File: CaptureSystemOutExtension.java    From junit-servers with MIT License 4 votes vote down vote up
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
	Parameter parameter = parameterContext.getParameter();
	Class<?> parameterType = parameter.getType();
	return CaptureSystemOut.class.isAssignableFrom(parameterType);
}
 
Example 18
Source File: DateParameterResolver.java    From festival with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean resolvable(Parameter parameter, RoutingContext routingContext) {
    return enable && parameter.isAnnotationPresent(Param.class) && parameter.getType() == Date.class;
}
 
Example 19
Source File: MultipartParamBinder.java    From oxygen with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supported(Parameter parameter) {
  return MultipartItem.class == parameter.getType();
}
 
Example 20
Source File: ExecuteArgAnalyzer.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
protected Class<?> prepareRootFormType(Parameter formParam) {
    return formParam != null ? formParam.getType() : null; // e.g. SeaForm, SeaBody, java.util.List
}