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

The following examples show how to use java.lang.reflect.Parameter#isNamePresent() . 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: 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 2
Source File: AnnotatedArgumentBuilder.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
protected String getArgumentName(Parameter parameter, AnnotatedType parameterType, ArgumentBuilderParams builderParams) {
    if (Optional.ofNullable(parameterType.getAnnotation(GraphQLId.class)).filter(GraphQLId::relayId).isPresent()) {
        return GraphQLId.RELAY_ID_FIELD_NAME;
    }
    GraphQLArgument meta = parameter.getAnnotation(GraphQLArgument.class);
    if (meta != null && !meta.name().isEmpty()) {
        return builderParams.getEnvironment().messageBundle.interpolate(meta.name());
    } else {
        if (!parameter.isNamePresent() && builderParams.getInclusionStrategy().includeArgumentForMapping(parameter, parameterType, builderParams.getDeclaringType())) {
            log.warn("No explicit argument name given and the parameter name lost in compilation: "
                    + parameter.getDeclaringExecutable().toGenericString() + "#" + parameter.toString()
                    + ". For details and possible solutions see " + Urls.Errors.MISSING_ARGUMENT_NAME);
        }
        return parameter.getName();
    }
}
 
Example 3
Source File: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void noParameterName() {
  Method method = ReflectUtils.findMethod(Schema.class, "testint");
  Parameter parameter = method.getParameters()[0];
  new Expectations(parameter) {
    {
      parameter.isNamePresent();
      result = false;
    }
  };

  expectedException.expect(IllegalStateException.class);
  expectedException.expectMessage(
      "parameter name is not present, method=org.apache.servicecomb.swagger.generator.core.schema.Schema:testint\n"
          + "solution:\n"
          + "  change pom.xml, add compiler argument: -parameters, for example:\n"
          + "    <plugin>\n"
          + "      <groupId>org.apache.maven.plugins</groupId>\n"
          + "      <artifactId>maven-compiler-plugin</artifactId>\n"
          + "      <configuration>\n"
          + "        <compilerArgument>-parameters</compilerArgument>\n"
          + "      </configuration>\n"
          + "    </plugin>");
  SwaggerGeneratorUtils.collectParameterName(parameter);
}
 
Example 4
Source File: Utils.java    From jboot with Apache License 2.0 5 votes vote down vote up
/**
 * use jfinal engine render text
 *
 * @param template
 * @param method
 * @param arguments
 * @return
 */
static String engineRender(String template, Method method, Object[] arguments) {
    Map<String, Object> datas = new HashMap();
    int x = 0;
    for (Parameter p : method.getParameters()) {
        if (!p.isNamePresent()) {
            // 必须通过添加 -parameters 进行编译,才可以获取 Parameter 的编译前的名字
            throw new RuntimeException(" Maven or IDE config is error. see http://www.jfinal.com/doc/3-3 ");
        }
        datas.put(p.getName(), arguments[x++]);
    }

    return ENGINE.getTemplateByString(template).renderToString(datas);

}
 
Example 5
Source File: StandardReflectionParameterNameDiscoverer.java    From spring4-understanding 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 6
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 7
Source File: FaweParanamer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String[] lookupParameterNames(AccessibleObject methodOrConstructor, boolean throwExceptionIfMissing) {
    Parameter[] params;
    if (methodOrConstructor instanceof Constructor) {
        params = ((Constructor) methodOrConstructor).getParameters();
    } else if (methodOrConstructor instanceof Method) {
        params = ((Method) methodOrConstructor).getParameters();
    } else {
        return super.lookupParameterNames(methodOrConstructor, throwExceptionIfMissing);
    }
    String[] names = new String[params.length];
    String[] defNames = null;
    for (int i = 0; i < names.length; i++) {
        Parameter param = params[i];
        if (param.isNamePresent()) {
            names[i] = param.getName();
        } else {
            if (defNames == null) {
                defNames = super.lookupParameterNames(methodOrConstructor, throwExceptionIfMissing);
                if (defNames.length == 0)
                    return defNames;
            }
            names[i] = defNames[i];
        }
    }
    return names;
}
 
Example 8
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 9
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 10
Source File: MockitoExtension.java    From sonar-gerrit-plugin 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 11
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 12
Source File: DefaultParameterNameProvider.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private List<String> getParameterNamesEx(Executable methodOrConstructor) {
  Parameter[] parameters = methodOrConstructor.getParameters();
  List<String> parameterNames = new ArrayList<>(parameters.length);
  for (int idx = 0; idx < parameters.length; idx++) {
    Parameter parameter = parameters[idx];
    String parameterName = parameter.isNamePresent() ? parameter.getName() : "arg" + idx;
    parameterNames.add(parameterName);
  }
  return Collections.unmodifiableList(parameterNames);
}
 
Example 13
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 14
Source File: SeMetricName.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
private String getParameterName(AnnotatedParameter<?> parameter) {
    Parameter[] parameters = ((Method) parameter.getDeclaringCallable().getJavaMember()).getParameters();
    Parameter param = parameters[parameter.getPosition()];
    if (param.isNamePresent()) {
        return param.getName();
    }
    else {
        throw new UnsupportedOperationException("Unable to retrieve name for parameter [" + parameter + "], activate the -parameters compiler argument or annotate the injected parameter with the @Metric annotation");
    }
}
 
Example 15
Source File: MockitoExtension.java    From jweb-cms with GNU Affero General Public License v3.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 16
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 17
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 18
Source File: StandardReflectionParameterNameDiscoverer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private String[] getParameterNames(Parameter[] parameters) {
	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 19
Source File: StandardReflectionParameterNameDiscoverer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private String[] getParameterNames(Parameter[] parameters) {
	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 20
Source File: Main.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
private static Map<String, Class<?>> fetchMissingSetters(Class<?> clazz) {        

        Map<String, Class<?>> setters = new HashMap<>();

        Field[] fields = clazz.getDeclaredFields();
        String[] names = new String[fields.length];
        Class<?>[] types = new Class<?>[fields.length];
        Arrays.setAll(names, i -> fields[i].getName());
        Arrays.setAll(types, i -> fields[i].getType());

        for (int i = 0; i < names.length; i++) {

            Field field = fields[i];
            boolean finalField = !Modifier.isFinal(field.getModifiers());

            if (finalField) {
                String setterAccessor = fetchSet(names[i]);

                try {
                    Method setter = clazz.getDeclaredMethod(setterAccessor, types[i]);

                    if (setter.getParameterCount() != 1
                            || !setter.getReturnType().equals(void.class)) {

                        setters.put(names[i], types[i]);
                        continue;
                    }

                    Parameter parameter = setter.getParameters()[0];

                    if ((parameter.isNamePresent() && !parameter.getName().equals(names[i]))
                            || !parameter.getType().equals(types[i])) {

                        setters.put(names[i], types[i]);
                    }

                } catch (NoSuchMethodException ex) {
                    setters.put(names[i], types[i]);
                    // System.err.println("No setter found for '" + names[i] + "' field");
                }
            }
        }

        return setters;
    }