Java Code Examples for java.lang.reflect.Method.getParameters()

The following are Jave code examples for showing how to use getParameters() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: spring-data-jdbc   File: JdbcAnnotatedRepositoryQueryCreator.java   View Source Code Vote up 6 votes
private void prepareQuery(JdbcQueryMethod method) {
    try {
        Method m = (Method) originalMethod.get(method);
        if (!m.isAnnotationPresent(Query.class)) {
            throw new IllegalStateException("Query annotation not present");
        }
        this.query = m.getAnnotation(Query.class).value();

        parameterKeys = new ArrayList<>(m.getParameterCount());
        for (Parameter parameter : m.getParameters()) {
            if (parameter.isAnnotationPresent(Param.class)) {
                parameterKeys.add(parameter.getAnnotation(Param.class).value());
            } else {
                parameterKeys.add(null);
            }
        }
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Project: bootstrap   File: JAXRSBeanValidationImplicitInInterceptor.java   View Source Code Vote up 6 votes
@Override
protected void handleValidation(final Message message, final Object resourceInstance, final Method method,
		final List<Object> arguments) {
	super.handleValidation(message, resourceInstance, method, arguments);

	// Check each parameter
	final Set<ConstraintViolation<?>> validationErrors = new HashSet<>();
	for (int index = 0; index < arguments.size(); index++) {
		final Parameter parameter = method.getParameters()[index];
		if (hasToBeValidated(parameter)) {
			// This parameter is a not context, path or query parameter
			validate(arguments.get(index), method, parameter, index, validationErrors);
		}
	}

	// Check the veto
	if (!validationErrors.isEmpty()) {
		message.put(FaultListener.class.getName(), new NoOpFaultListener());
		throw new ConstraintViolationException(validationErrors);
	}
}
 
Example 3
Project: fluid   File: Fluid.java   View Source Code Vote up 6 votes
private void invoke(Object mediator, Method method) {
  method = ReflectionHelper.makeAccessibleIfNot(method);

  List<Object> values = new ArrayList<>();
  for (Parameter param : method.getParameters()) {
    Port port = param.getAnnotation(Port.class);
    if (port != null) {
      String name = port.value();
      if (param.getType().isAssignableFrom(Sink.class)) {
        values.add(getSinkOrFail(name));
      } else if (param.getType().isAssignableFrom(Source.class)) {
        values.add(getSourceOrFail(name));
      }
    } else {
      throw new IllegalArgumentException("Invalid parameter - one parameter of " + method.getName()
        + " is not annotated with @Port");
    }
  }

  try {
    method.invoke(mediator, values.toArray());
  } catch (Exception e) {
    throw new IllegalStateException("Unable to invoke " + method.getName() + " from " + mediator.getClass()
      .getName(), e);
  }
}
 
Example 4
Project: 8R-Reflections   File: ClassWrapperTest.java   View Source Code Vote up 6 votes
@Test
public void testGetGenericType() throws Exception {
	Field genericInterfaceField = ClassWrapper.wrap(Foo.class).getField("genericInterface");

	assertEquals(Integer.class, getGenericType(genericInterfaceField, GenericInterface.class, 0));

	ClassWrapper<Foo> classWrapper = ClassWrapper.wrap(Foo.class);
	Field subGenericInterfaceField = classWrapper.getField("subGenericInterface");
	assertEquals(Long.class, getGenericType(subGenericInterfaceField, GenericInterface.class, 0));

	assertEquals(Long.class, getGenericType(Bar.class, GenericInterface.class, 0));

	assertEquals(Boolean.class, getGenericType(Bar.class, GenericClass.class, 0));

	Method method = classWrapper.getCompatibleMethodWithTypes("getBar", SubGenericInterface.class);
	assertEquals(Long.class, getGenericReturnType(method, GenericInterface.class, 0));

	Parameter parameter = method.getParameters()[0];
	assertEquals(Long.class, getGenericType(parameter, GenericInterface.class, 0));
}
 
Example 5
Project: drinkwater-java   File: RouteBuilders.java   View Source Code Vote up 6 votes
public static String formatBeanEndpointRoute(Method m) {
    String answer = m.getName();

    Parameter[] params = m.getParameters();
    java.util.List<String> paramList = new ArrayList<>();

    if (params.length > 0) {

        paramList.add("${body}");
        for (int i = 1; i < params.length; i++) {
            paramList.add("${header.param" + i + "}");
        }
    }

    answer = answer + "(" + String.join(",", paramList) + ")";

    return answer;
}
 
Example 6
Project: xm-commons   File: LepServiceHandler.java   View Source Code Vote up 6 votes
private LepMethod buildLepMethod(Class<?> targetType, Object target, Method method, Object[] args) {
    DefaultMethodSignature signature = new DefaultMethodSignature();
    signature.setName(method.getName());
    signature.setModifiers(method.getModifiers());
    signature.setDeclaringClass(targetType);
    signature.setParameterTypes(method.getParameterTypes());
    signature.setExceptionTypes(method.getExceptionTypes());
    signature.setReturnType(method.getReturnType());
    signature.setMethod(method);

    Parameter[] parameters = method.getParameters();
    String[] parameterNames;
    if (parameters == null) {
        parameterNames = new String[0];
    } else {
        parameterNames = new String[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            Parameter p = parameters[i];
            // p.isNamePresent()
            parameterNames[i] = p.getName();
        }
    }
    signature.setParameterNames(parameterNames);

    return new DefaultLepMethod(target, signature, args);
}
 
Example 7
Project: mbed-cloud-sdk-java   File: APIMappingGenerator.java   View Source Code Vote up 6 votes
private APIMethod recordAPIMethod(Method method) {
    if (method == null || !method.isAnnotationPresent(API.class)) {
        return null;
    }
    APIMethod m = new APIMethod(method.getName());
    if (method.getParameterCount() > 0) {
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            String defaultValue = determineParameterDefaultValue(parameter);
            determineContentType(parameter);
            APIMethodArgument arg = new APIMethodArgument(parameter.getName(), parameter.getType(),
                    determineContentType(parameter), defaultValue);
            m.addArgument(arg);
        }
    }
    APIMethodArgument returnArg = new APIMethodArgument(method.getReturnType(), null);
    m.setReturnArgument(returnArg);
    return m;
}
 
Example 8
Project: chopsticks   File: MethodArgument.java   View Source Code Vote up 6 votes
public static Object[] getArgs(Signature signature) throws Exception {
	Method actionMethod = signature.getAction();
	Request request = signature.request();
	actionMethod.setAccessible(true);

	Parameter[] parameters = actionMethod.getParameters();
	Object[] args = new Object[parameters.length];
	String[] parameterNames = AsmKit.getMethodParamNames(actionMethod);

	for (int i = 0, len = parameters.length; i < len; i++) {
		Parameter parameter = parameters[i];
		String paramName = parameterNames[i];
		Class<?> argType = parameter.getType();
		if (containsAnnotation(parameter)) {
			args[i] = getAnnotationParam(parameter, paramName, request);
			continue;
		}
		if (ReflectKit.isPrimitive(argType)) {
			args[i] = request.query(paramName);
			continue;
		}
		args[i] = getCustomType(parameter, signature);
	}
	return args;
}
 
Example 9
Project: algorithm.annotation   File: AlgorithmServiceImpl.java   View Source Code Vote up 6 votes
@Override
public List<String> describeAlgorithm(String name) throws TException {
	List<String> ret = new ArrayList<>();
	Class<?> clazz = map.get(name);
	if(clazz == null){
		throw new RuntimeException("No such algorithm!");
	}
	for (final Method method : clazz.getDeclaredMethods()){
		final Algorithm my= method.getAnnotation(Algorithm.class); 
		if ((null != my) && my.name().equals(name)){
			ret.add("Algorithm Name:" + name);
			ret.add("Return Type:" + method.getReturnType().toString());
			for(Parameter param : method.getParameters()){
				ret.add(param.toString());
			}
		}
	}
	return ret;
}
 
Example 10
Project: litiengine   File: ConfigurationGroup.java   View Source Code Vote up 5 votes
private Method getSetter(final String fieldName) {
  for (final Method method : this.getClass().getMethods()) {
    // method must start with "set" and have only one parameter, mathich the
    // specified fieldType
    if (method.getName().equalsIgnoreCase("set" + fieldName) && method.getParameters().length == 1) {
      if (!method.isAccessible()) {
        method.setAccessible(true);
      }

      return method;
    }
  }

  return null;
}
 
Example 11
Project: drinkwater-java   File: RestHelper.java   View Source Code Vote up 5 votes
private static boolean isMultipartBody(Method method) {

        if (method.getParameters().length > 0) {
            Class type = method.getParameters()[0].getType();
            if (type.isAssignableFrom(InputStream.class)) {
                return true;
            }
        }
        return false;
    }
 
Example 12
Project: gauravbytes   File: Java8MethodParameters.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
	Class<Java8MethodParameters> clazz = Java8MethodParameters.class;
	Method[] methods = clazz.getDeclaredMethods();
	for (Method method : methods) {
		System.out.println(method.getName());
		for (Parameter parameter : method.getParameters()) {
			System.out.println(parameter.getName());
		}
	}
}
 
Example 13
Project: MoMuOSB   File: GetAnnotation.java   View Source Code Vote up 5 votes
/**
 * Parse Class Anotation to Method
 * @param clazz Class
 * @return A Collection of Annotation and Methods
 */
public static HashMap<Command, Method> getCommandAnnotation(Class clazz, Module instance){
    HashMap<Command, Method> allannotation = new HashMap<>();
    Console.debug("----------------Module: "+clazz.getName()+"----------------");
    try {
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                Command annotation = method.getAnnotation(Command.class);
                LanguageMethod language = method.getAnnotation(LanguageMethod.class);
                if (annotation != null) {
                    if (method.getParameters().length == 2) {
                        if (method.getParameters()[0].getParameterizedType().equals(MessageReceivedEvent.class) && method.getParameters()[1].getParameterizedType().equals(String[].class)) {
                            Console.debug("Command: " + annotation.prefix()+annotation.command()+" in "+method.getName());
                            allannotation.put(annotation, method);
                            PERM.addPermission(annotation);
                        } else {
                            Console.error("Method has no valid Parameters: "+method.getName());
                        }
                    } else {
                        Console.error("Method has no valid Parameters Count: "+method.getName());
                    }
                } else if (language != null) {
                    Console.debug("Language: " + language.languagestringcount()+" in "+method.getName()+"   "+clazz.getName()+"   "+instance.getClass().getName());
                    COMMAND.languages.put(language, method);
                    COMMAND.langinstances.put(language, instance);
                }
            }
    } catch (Exception ex) {
        Console.error(String.format(LANG.getTranslation("annotation_error"), clazz.getName(), ex.getMessage()));
        Console.error(ex);
    }
    return allannotation;
}
 
Example 14
Project: echidna   File: Resource.java   View Source Code Vote up 5 votes
/**
 * Find all handler mehtods of the resource.
 *
 * @param resourceInstance The instance.
 */
private void findResourceMethods(Object resourceInstance) {
	for (Method declaredMethod : resourceInstance.getClass().getDeclaredMethods()) {
		Path methodPath = declaredMethod.getAnnotation(Path.class);
		
		if (methodPath == null) {
			continue;
		}
		
		Consumes consumes = declaredMethod.getAnnotation(Consumes.class);
		Produces produces = declaredMethod.getAnnotation(Produces.class);
		
		HTTPMethod method = HTTPMethod.GET;
		
		if (declaredMethod.isAnnotationPresent(POST.class)) {
			method = HTTPMethod.POST;
		} else if (declaredMethod.isAnnotationPresent(DELETE.class)) {
			method = HTTPMethod.DELETE;
		} else if (declaredMethod.isAnnotationPresent(PUT.class)) {
			method = HTTPMethod.PUT;
		} else if (declaredMethod.isAnnotationPresent(PATCH.class)) {
			method = HTTPMethod.PATCH;
		}
		
		ResourceMethod resourceMethod = new ResourceMethod(methodPath.value(), method,
			consumes.value(), produces.value(), declaredMethod, resourceInstance);
		
		for (Parameter parameter : declaredMethod.getParameters()) {
			if (parameter.isAnnotationPresent(PostKey.class)) {
				resourceMethod.addPostParam(parameter.getAnnotation(PostKey.class).value());
			}
		}
		
		this.resourceMethods.put(methodPath.value(), resourceMethod);
	}
}
 
Example 15
Project: RestyPass   File: SpringAnnotationWrapper.java   View Source Code Vote up 4 votes
/**
 * Process annotations on params.
 *
 * @param requestTemplate the request template
 * @param method          the method
 */
protected void processAnnotationsOnParams(RestyRequestTemplate requestTemplate, Method method) {
    for (int i = 0; i < method.getParameters().length; i++) {
        Parameter parameter = method.getParameters()[i];
        // 处理PathVariable
        PathVariable pathVariable = findMergedAnnotation(parameter, PathVariable.class);
        if (pathVariable != null) {
            PathVariableData pathVariableData = new PathVariableData();
            pathVariableData.setIndex(i);
            pathVariableData.setName("{" + (StringUtils.isNotEmpty(pathVariable.name()) ? pathVariable.name() : parameter.getName()) + "}");
            pathVariableData.setRequired(pathVariable.required());
            requestTemplate.addPathVariable(pathVariableData);
            continue;
        }
        // 处理RequestParam
        RequestParam requestParam = findMergedAnnotation(parameter, RequestParam.class);
        if (requestParam != null) {
            RequestParamData requestParamData = new RequestParamData();
            requestParamData.setIndex(i);
            requestParamData.setName(StringUtils.isNotEmpty(requestParam.name()) ? requestParam.name() : parameter.getName());
            requestParamData.setRequired(requestParam.required());
            requestParamData.setDefaultValue(resolveDefaultValue(requestParam.defaultValue()));
            requestTemplate.addRequestParam(requestParamData);
            continue;
        }

        RequestHeader requestHeader = findMergedAnnotation(parameter, RequestHeader.class);
        if (requestHeader != null) {
            RequestHeaderData requestHeaderData = new RequestHeaderData();
            requestHeaderData.setIndex(i);
            requestHeaderData.setName(StringUtils.isNotEmpty(requestHeader.name()) ? requestHeader.name() : parameter.getName());
            requestHeaderData.setRequired(requestHeader.required());
            requestHeaderData.setDefaultValue(resolveDefaultValue(requestHeader.defaultValue()));
            requestTemplate.addRequestHeader(requestHeaderData);
            continue;
        }

        // 处理RequestBody和无注解参数
        RequestBody requestBody = findMergedAnnotation(parameter, RequestBody.class);
        if ((requestBody != null || parameter.getAnnotations().length == 0)
                && parameter.getType() != RestyFuture.class) {
            RequestBodyData requestBodyData = new RequestBodyData();
            requestBodyData.setIndex(i);
            requestBodyData.setName(parameter.getName());
            requestBodyData.setDefaultValue(null);
            if (requestBody != null) {
                requestBodyData.setRequired(requestBody.required());
            } else {
                requestBodyData.setRequired(false);
            }
            requestTemplate.addRequestBody(requestBodyData);
        }
    }
}
 
Example 16
Project: aws-sdk-java-v2   File: ConfigurationBuilderTest.java   View Source Code Vote up 4 votes
private boolean matchesSignature(String methodName, PropertyDescriptor property, Method builderMethod) {
    return builderMethod.getName().equals(methodName) &&
           builderMethod.getParameters().length == 1 &&
           builderMethod.getParameters()[0].getType().equals(property.getPropertyType());
}
 
Example 17
Project: SamaGamesAPI   File: Generator.java   View Source Code Vote up 4 votes
public static TypeSpec createInterfaceOfType(Class type, boolean useIncrement, boolean isUpdatable)
{
    String name = "I" +type.getSimpleName().replaceAll("Bean", "");

    TypeSpec.Builder object = TypeSpec.interfaceBuilder(name)
            .addModifiers(Modifier.PUBLIC);
    object.addJavadoc(header);
    if (isUpdatable)
    {
        object.addMethod(getMethod("update", void.class));
        object.addMethod(getMethod("refresh", void.class));
    }

    Method[] subDeclaredMethods = type.getDeclaredMethods();
    for (Method method : subDeclaredMethods)
    {
        String methodName = method.getName();
        if (method.getParameters().length > 0)
        {
            if (methodName.startsWith("set") && useIncrement)
            {
                boolean isIncrementable = false;
                Class<?> type1 = method.getParameters()[0].getType();
                if (type1.equals(int.class)
                        || type1.equals(long.class)
                        || type1.equals(double.class)
                        || type1.equals(float.class))
                    isIncrementable = true;

                if (isIncrementable)
                {
                    methodName = "incrBy" + methodName.substring(3);
                }
            }

        }

        MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName);
        if (method.getParameterCount() > 0)
        {
            for (Parameter parameter : method.getParameters())
            {
                builder.addParameter(parameter.getType(), parameter.getName());
            }
        }
        builder.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);
        builder.returns(method.getReturnType());
        object.addMethod(builder.build());
    }
    return object.build();
}
 
Example 18
Project: kurdran   File: HttpServerHandler.java   View Source Code Vote up 4 votes
private Object[] handleArg(MethodInfo methodInfo, HttpRequest request) {

        //处理传来的参数
        Map<String, List<String>> params = request.getParamsMap();

        Method method = methodInfo.getInvokeMethod();


        Parameter[] parameters = method.getParameters();


        Arrays.stream(parameters).forEach(p-> System.out.println(p.getName()));

        //储存传来的参数
        List<Object> realParamList = new ArrayList<>(method.getParameterCount());

        Arrays.stream(parameters).forEach(p -> realParamList.add(params.get(p.getName()).get(0)));

        return realParamList.toArray();
    }
 
Example 19
Project: easysocket   File: ApiUtil.java   View Source Code Vote up 4 votes
/**
 * 构建resource
 * 
 * @param instance
 *            resource实例
 * @param resourceMethod
 *            resource方法
 * @param resourceClass
 *            resource类
 * @return resource 根据指定参数构建的资源
 */
public static Resource buildResource(Object instance, Class<?> resourceClass, Method resourceMethod) {
	// 获取API参数
	Parameter[] parameters = resourceMethod.getParameters();
	List<Param<?>> params = new ArrayList<>(parameters.length);
	for (Parameter parameter : parameters) {
		Param<?> param = createParam(parameter.getType());
		params.add(param);

		JavaType type = JavaTypeUtil.createJavaType(parameter.getParameterizedType());
		type.setAnnotations(parameter.getAnnotations());
		param.setType(type);

		try {
			param.setName(getParamName(parameter));
		} catch (ParamterNoNamingException e) {
			if (singleton(parameters)) {
				// 如果只有一个参数,那么允许不命名
				param.setName("default");
				Annotation[] old = type.getAnnotations();
				Annotation[] now = new Annotation[old.length + 1];
				System.arraycopy(old, 0, now, 0, old.length);
				now[old.length] = defaultGeneralParam;
				type.setAnnotations(now);
			} else {
				throw e;
			}
		}
	}

	resourceMethod.setAccessible(true);

	Resource resource = new Resource();
	resource.setName(getURI(resourceMethod, resourceClass));
	resource.setConsume(getConsume(resourceMethod));
	resource.setProduce(getProduce(resourceMethod));
	resource.setParams(params);
	resource.setResourceClass(resourceClass);
	resource.setResourceMethod(resourceMethod);
	resource.setInstance(instance);
	return resource;
}
 
Example 20
Project: RuntimeTransformer   File: MethodUtils.java   View Source Code Vote up 3 votes
public static String getSignature(Method method) {
    StringBuilder signature = new StringBuilder();

    signature.append('(');

    for (Parameter parameter : method.getParameters()) {
        signature.append(translateTypeToInternal(parameter.getType()));
    }

    signature.append(')');

    signature.append(translateTypeToInternal(method.getReturnType()));

    return signature.toString();
}