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

The following examples show how to use java.lang.reflect.Parameter#getName() . 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: ComponentDescriptor.java    From fenixedu-cms with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Component instantiate(JsonObject params) throws Exception {
    Object[] arguments = new Object[ctor.getParameterCount()];
    for (int i = 0; i < ctor.getParameterCount(); i++) {
        Parameter parameter = ctor.getParameters()[i];
        ComponentParameterDescriptor descriptor = parameters.get(parameter.getName());
        String value = params.has(parameter.getName()) ? params.get(parameter.getName()).getAsString() : null;

        Class<?> type = parameter.getType();
        Object coercedValue = descriptor.type.coerce(type, value);

        if (coercedValue == null && descriptor.isRequired()) {
            throw new IllegalArgumentException("Required parameter " + parameter.getName() + " was not found!");
        }

        arguments[i] = coercedValue;
    }
    return (Component) ctor.newInstance(arguments);
}
 
Example 2
Source File: AnnotatedElementNameUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static String getName(Object element) {
    if (element instanceof Parameter) {
        final Parameter parameter = (Parameter) element;
        if (!parameter.isNamePresent()) {
            throw new IllegalArgumentException(
                    "cannot obtain the name of the parameter or field automatically. " +
                    "Please make sure you compiled your code with '-parameters' option. " +
                    "If not, you need to specify parameter and header names with @" +
                    Param.class.getSimpleName() + " and @" + Header.class.getSimpleName() + '.');
        }
        return parameter.getName();
    }
    if (element instanceof Field) {
        return ((Field) element).getName();
    }
    throw new IllegalArgumentException("cannot find the name: " + element.getClass().getName());
}
 
Example 3
Source File: AnnotationMethodToParameterNamesFunction.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
@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]);
}
 
Example 4
Source File: GenericConstraintRule.java    From BlogManagePlatform with 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 5
Source File: MockitoExtension.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    }
    else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
 
Example 6
Source File: ParamUtils.java    From RestDoc with Apache License 2.0 5 votes vote down vote up
/**
 * 从缓存的map寻找参数名
 */
public static String discoverParameterName(Parameter parameter) {
    if (parameter == null) return null;

    String parameterName = parameterNameMap.get(parameter);
    if (parameterName != null) {
        parameterNameMap.remove(parameter);
    } else {
        parameterName = parameter.getName();
    }
    return parameterName;

}
 
Example 7
Source File: StandardReflectionParameterNameDiscoverer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String[] getParameterNames(Method method) {
	Parameter[] parameters = method.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 8
Source File: Reflection.java    From openCypher with Apache License 2.0 5 votes vote down vote up
/**
 * Get the parameter name of a ({@linkplain Serializable serializable}) lambda with a single parameter.
 * <p>
 * Getting the parameter requires the source to be compiled with the {@code -parameters} flag passed to {@code
 * javac} and JDK {@code 1.8.0_60} or newer.
 *
 * @param lambda the ({@linkplain Serializable serializable}) lambda to get the parameter name from.
 * @return the name of the sole parameter of the lambda.
 */
public static String lambdaParameterName( Serializable lambda )
{
    SerializedLambda serialized = serializedLambda( lambda );
    Parameter[] parameters = lambdaMethod( serialized ).getParameters();
    int bound;
    switch ( serialized.getImplMethodKind() )
    {
    case REF_invokeStatic:
        bound = serialized.getCapturedArgCount();
        break;
    case REF_invokeSpecial:
        bound = serialized.getCapturedArgCount() - 1;
        break;
    default:
        throw new IllegalArgumentException( "Unsupported method kind: " + serialized.getImplMethodKind() );
    }
    if ( parameters == null || (parameters.length - bound) != 1 )
    {
        throw new IllegalArgumentException(
                "Must have exactly one parameter, not " + (parameters == null ? 0 : parameters.length) +
                "; " + Arrays.toString( parameters ) + ", bound: " + bound );
    }
    Parameter parameter = parameters[bound];
    if ( !parameter.isNamePresent() )
    {
        throw new IllegalStateException(
                "No parameter name present, compile with '-parameters', and use JDK 1.8.0_60 or newer. " +
                "Your JDK version is " + System.getProperty( "java.version" ) );
    }
    return parameter.getName();
}
 
Example 9
Source File: CTestStructure.java    From lin-check with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static ParameterGenerator<?> getOrCreateGenerator(Method m, Parameter p, String nameInOperation,
    Map<String, ParameterGenerator<?>> namedGens)
{
    // Read @Param annotation on the parameter
    Param paramAnn = p.getAnnotation(Param.class);
    // If this annotation not presented use named generator based on name presented in @Operation or parameter name.
    if (paramAnn == null) {
        // If name in @Operation is presented, return the generator with this name,
        // otherwise return generator with parameter's name
        String name = nameInOperation != null ? nameInOperation :
            (p.isNamePresent() ? p.getName() : null);
        if (name != null)
            return checkAndGetNamedGenerator(namedGens, name);
        // Parameter generator is not specified, try to create a default one
        ParameterGenerator<?> defaultGenerator = createDefaultGenerator(p);
        if (defaultGenerator != null)
            return defaultGenerator;
        // Cannot create default parameter generator, throw an exception
        throw new IllegalStateException("Generator for parameter \'" + p + "\" in method \""
            + m.getName() + "\" should be specified.");
    }
    // If the @Param annotation is presented check it's correctness firstly
    if (!paramAnn.name().isEmpty() && !(paramAnn.gen() == ParameterGenerator.Dummy.class))
        throw new IllegalStateException("@Param should have either name or gen with optionally configuration");
    // If @Param annotation specifies generator's name then return the specified generator
    if (!paramAnn.name().isEmpty())
        return checkAndGetNamedGenerator(namedGens, paramAnn.name());
    // Otherwise create new parameter generator
    return createGenerator(paramAnn);
}
 
Example 10
Source File: StandardReflectionParameterNameDiscoverer.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: LegalEnumRule.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@Override
public void check(Method method) throws CodeCheckException {
	for (Parameter parameter : method.getParameters()) {
		MapEnum annotation = parameter.getAnnotation(MapEnum.class);
		if (annotation != null) {
			if (!ClassUtils.isPrimitiveOrWrapper(parameter.getType())) {
				throw new CodeCheckException("方法", ReflectUtil.fullName(method), "的参数", parameter.getName(), "不是基本类型或者其装箱类,不能使用@",
					MapEnum.class.getCanonicalName(), "注解");
			}
			checkLegalEnum(annotation);
		}
	}
}
 
Example 12
Source File: MockitoExtension.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 5 votes vote down vote up
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
 
Example 13
Source File: MockitoExtension.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    }
    else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
 
Example 14
Source File: AnnotatedServiceFactory.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the description of the specified {@link AnnotatedElement}.
 */
@Nullable
static String findDescription(AnnotatedElement annotatedElement) {
    requireNonNull(annotatedElement, "annotatedElement");
    final Description description = AnnotationUtil.findFirst(annotatedElement, Description.class);
    if (description != null) {
        final String value = description.value();
        if (DefaultValues.isSpecified(value)) {
            checkArgument(!value.isEmpty(), "value is empty.");
            return value;
        }
    } else if (annotatedElement instanceof Parameter) {
        // JavaDoc/KDoc descriptions only exist for method parameters
        final Parameter parameter = (Parameter) annotatedElement;
        final Executable executable = parameter.getDeclaringExecutable();
        final Class<?> clazz = executable.getDeclaringClass();
        final String fileName = getFileName(clazz.getCanonicalName());
        final String propertyName = executable.getName() + '.' + parameter.getName();
        final Properties cachedProperties = DOCUMENTATION_PROPERTIES_CACHE.getIfPresent(fileName);
        if (cachedProperties != null) {
            return cachedProperties.getProperty(propertyName);
        }
        try (InputStream stream = AnnotatedServiceFactory.class.getClassLoader()
                                                               .getResourceAsStream(fileName)) {
            if (stream == null) {
                return null;
            }
            final Properties properties = new Properties();
            properties.load(stream);
            DOCUMENTATION_PROPERTIES_CACHE.put(fileName, properties);
            return properties.getProperty(propertyName);
        } catch (IOException exception) {
            logger.warn("Failed to load an API description file: {}", fileName, exception);
        }
    }
    return null;
}
 
Example 15
Source File: DeclarativeContract.java    From feign with Apache License 2.0 5 votes vote down vote up
/**
 * @param data metadata collected so far relating to the current java method.
 * @param annotations annotations present on the current parameter annotation.
 * @param paramIndex if you find a name in {@code annotations}, call
 *        {@link #nameParam(MethodMetadata, String, int)} with this as the last parameter.
 * @return true if you called {@link #nameParam(MethodMetadata, String, int)} after finding an
 *         http-relevant annotation.
 */
@Override
protected final boolean processAnnotationsOnParameter(MethodMetadata data,
                                                      Annotation[] annotations,
                                                      int paramIndex) {
  List<Annotation> matchingAnnotations = Arrays.stream(annotations)
      .filter(
          annotation -> parameterAnnotationProcessors.containsKey(annotation.annotationType()))
      .collect(Collectors.toList());

  if (!matchingAnnotations.isEmpty()) {
    matchingAnnotations.forEach(annotation -> parameterAnnotationProcessors
        .getOrDefault(annotation.annotationType(), ParameterAnnotationProcessor.DO_NOTHING)
        .process(annotation, data, paramIndex));

  } else {
    final Parameter parameter = data.method().getParameters()[paramIndex];
    String parameterName = parameter.isNamePresent()
        ? parameter.getName()
        : parameter.getType().getSimpleName();
    if (annotations.length == 0) {
      data.addWarning(String.format(
          "Parameter %s has no annotations, it may affect contract %s",
          parameterName,
          getClass().getSimpleName()));
    } else {
      data.addWarning(String.format(
          "Parameter %s has annotations %s that are not used by contract %s",
          parameterName,
          Arrays.stream(annotations)
              .map(annotation -> annotation.annotationType()
                  .getSimpleName())
              .collect(Collectors.toList()),
          getClass().getSimpleName()));
    }
  }
  return false;
}
 
Example 16
Source File: ControllerUtils.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of a parameter.
 *
 * @param parameter
 * @return the name of a parameter.
 */
public static String getParameterName(Parameter parameter) {
    // identify parameter name and pattern from controllerMethod signature
    String methodParameterName = parameter.getName();
    if (parameter.isAnnotationPresent(Param.class)) {
        Param param = parameter.getAnnotation(Param.class);
        if (!StringUtils.isNullOrEmpty(param.value())) {
            methodParameterName = param.value();
        }
    }

    return methodParameterName;
}
 
Example 17
Source File: RestDocParser.java    From RestDoc with Apache License 2.0 5 votes vote down vote up
private PathModel handleMethod(Method method, MethodJavadoc methodJavadoc) {
    for (var methodResolver : _configuration.getMethodFilters()) {
        if (!methodResolver.isSupport(method))
            return null;
    }


    var pathModel = new PathModel();
    for (var methodParser : _configuration.getMethodParsers()) {
        pathModel = methodParser.parse(method, methodJavadoc, pathModel);
    }
    String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);
    Parameter[] parameters = method.getParameters();

    for (int i = 0; i < parameters.length; i++) {
        ParamJavadoc paramJavadoc = null;
        Parameter parameter = parameters[i];
        String parameterName;
        if (!parameter.isNamePresent() && parameterNames != null) {
            parameterName = parameterNames[i];
            ParamUtils.cacheParameterName(parameter, parameterName);
        } else {
            parameterName = parameter.getName();
        }
        if (methodJavadoc != null) {
            paramJavadoc = methodJavadoc.getParams().stream().filter(o -> o.getName().equals(parameterName)).findFirst().orElse(null);
        }
        var parameterModel = handleMethodParameter(parameter, paramJavadoc);
        if (parameterModel != null)
            pathModel.getParameters().add(parameterModel);

    }
    Comment returnComment = null;
    if (methodJavadoc != null)
        returnComment = methodJavadoc.getReturns();
    var responseModels = handleReturnValue(method, returnComment);
    pathModel.setResponse(responseModels);
    return pathModel;
}
 
Example 18
Source File: ByteBuddyUtils.java    From beam with Apache License 2.0 4 votes vote down vote up
protected InvokeUserCreateInstruction(
    List<FieldValueTypeInformation> fields,
    Class targetClass,
    List<Parameter> parameters,
    TypeConversionsFactory typeConversionsFactory) {
  this.fields = fields;
  this.targetClass = targetClass;
  this.parameters = parameters;
  this.typeConversionsFactory = typeConversionsFactory;

  // Method parameters might not be in the same order as the schema fields, and the input
  // array to SchemaUserTypeCreator.create is in schema order. Examine the parameter names
  // and compare against field names to calculate the mapping between the two lists.
  Map<String, Integer> fieldsByLogicalName = Maps.newHashMap();
  Map<String, Integer> fieldsByJavaClassMember = Maps.newHashMap();
  for (int i = 0; i < fields.size(); ++i) {
    // Method parameters are allowed to either correspond to the schema field names or to the
    // actual Java field or method names.
    FieldValueTypeInformation fieldValue = checkNotNull(fields.get(i));
    fieldsByLogicalName.put(fieldValue.getName(), i);
    if (fieldValue.getField() != null) {
      fieldsByJavaClassMember.put(fieldValue.getField().getName(), i);
    } else if (fieldValue.getMethod() != null) {
      String name = ReflectUtils.stripPrefix(fieldValue.getMethod().getName(), "set");
      fieldsByJavaClassMember.put(name, i);
    }
  }

  fieldMapping = Maps.newHashMap();
  for (int i = 0; i < parameters.size(); ++i) {
    Parameter parameter = parameters.get(i);
    String paramName = parameter.getName();
    Integer index = fieldsByLogicalName.get(paramName);
    if (index == null) {
      index = fieldsByJavaClassMember.get(paramName);
    }
    if (index == null) {
      throw new RuntimeException(
          "Creator parameter " + paramName + " Doesn't correspond to a schema field");
    }
    fieldMapping.put(i, index);
  }
}
 
Example 19
Source File: PoseidonLegoSet.java    From Poseidon with Apache License 2.0 4 votes vote down vote up
private void resolveInjectableConstructorDependencies(Constructor<?> constructor, Object[] initParams, int offset, Optional<Request> request) throws MissingInformationException, ElementNotFoundException {
    for (int i = offset; i < constructor.getParameterCount(); i++) {
        final Parameter constructorParameter = constructor.getParameters()[i];
        final RequestAttribute requestAttribute = constructorParameter.getAnnotation(RequestAttribute.class);
        final com.flipkart.poseidon.datasources.ServiceClient serviceClientAttribute = constructorParameter.getAnnotation(com.flipkart.poseidon.datasources.ServiceClient.class);
        final SystemDataSource systemDataSourceAttribute = constructorParameter.getAnnotation(SystemDataSource.class);
        if (requestAttribute != null) {
            final String attributeName = StringUtils.isNullOrEmpty(requestAttribute.value()) ? constructorParameter.getName() : requestAttribute.value();
            initParams[i] = request.map(r -> r.getAttribute(attributeName)).map(attr -> {
                if (constructorParameter.getType().isAssignableFrom(attr.getClass())) {
                    return attr;
                } else {
                    return mapper.convertValue(attr, mapper.constructType(constructorParameter.getParameterizedType()));
                }
            }).orElse(null);
        } else if (serviceClientAttribute != null) {
            ServiceClient serviceClient = serviceClientsByName.get(constructor.getParameterTypes()[i].getName());
            if (serviceClient == null) {
                throw new ElementNotFoundException("Unable to find ServiceClient for class = " + constructor.getParameterTypes()[i]);
            }
            initParams[i] = serviceClient;
        } else if (systemDataSourceAttribute != null) {
            final DataSource<?> systemDataSource = systemDataSources.get(systemDataSourceAttribute.value());
            if (systemDataSource == null) {
                throw new ElementNotFoundException("Unable to find SystemDataSource for id = " + systemDataSourceAttribute.value());
            }
            initParams[i] = systemDataSource;
        } else {
            final Qualifier qualifier = constructorParameter.getAnnotation(Qualifier.class);
            String beanName = null;
            if (qualifier != null && !StringUtils.isNullOrEmpty(qualifier.value())) {
                beanName = qualifier.value();
            }

            initParams[i] = beanName == null ? context.getBean(constructor.getParameterTypes()[i]) : context.getBean(beanName, constructor.getParameterTypes()[i]);
            if (initParams[i] == null) {
                throw new MissingInformationException("Unmet dependency for constructor " + constructor.getName() + ": " + constructor.getParameterTypes()[i].getCanonicalName());
            }
        }
    }
}
 
Example 20
Source File: TypeMappingException.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public static TypeMappingException ambiguousParameterType(Executable executable, Parameter parameter, Exception cause) {
    return new TypeMappingException("Parameter \"" + parameter.getName() + "\" of method \"" + executable.getName() +
            "\" is missing generic type parameters and can not be mapped." +
            " For details and possible solutions see " + Urls.Errors.AMBIGUOUS_PARAMETER_TYPE, cause);
}