Java Code Examples for java.lang.reflect.Method#getParameters()
The following examples show how to use
java.lang.reflect.Method#getParameters() .
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: ApiBeta.java From attic-aurora with Apache License 2.0 | 6 votes |
/** * Parses method parameters into the appropriate types. For a method call to be successful, * the elements supplied in the request must match the names of those specified in the thrift * method definition. If a method parameter does not exist in the request object, {@code null} * will be substituted. * * @param json Incoming request data, to translate into method parameters. * @param method The thrift method to bind parameters for. * @return Parsed method parameters. * @throws WebApplicationException If a parameter could not be parsed. */ private Object[] readParams(JsonObject json, Method method) throws WebApplicationException { List<Object> params = Lists.newArrayList(); for (Parameter param : method.getParameters()) { try { params.add(GSON.fromJson(getJsonMember(json, param.getName()), param.getType())); } catch (JsonParseException e) { throw new WebApplicationException( e, badRequest("Failed to parse parameter " + param + ": " + e.getMessage())); } } return params.toArray(); }
Example 2
Source File: ServiceVerticle.java From vert.x-microservice with Apache License 2.0 | 6 votes |
private Object[] invokeObjectEBParameters(Message<Object> m, Method method) { final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); int counter = 0; for (java.lang.reflect.Parameter p : parameters) { if (p.getType().equals(EBMessageReply.class)) { final String consumesVal = consumes != null && consumes.value().length > 0 ? consumes.value()[0] : ""; parameterResult[counter] = new EBMessageReply(this.vertx.eventBus(), m, consumesVal, getConverter()); } else { if (TypeTool.isCompatibleType(p.getType())) { parameterResult[counter] = p.getType().cast(m.body()); } else { parameterResult[counter] = getConverter().convertToObject(String.valueOf(m.body()), p.getType()); } } counter++; } return parameterResult; }
Example 3
Source File: ServiceVerticle.java From vert.x-microservice with Apache License 2.0 | 6 votes |
private Object[] invokeBinaryEBParameters(Message<byte[]> m, Method method) { byte[] tmp = m.body(); final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); int i = 0; for (java.lang.reflect.Parameter p : parameters) { if (p.getType().equals(EBMessageReply.class)) { final String consumesVal = consumes != null && consumes.value().length > 0 ? consumes.value()[0] : ""; parameterResult[i] = new EBMessageReply(this.vertx.eventBus(), m, consumesVal, getConverter()); } else { putTypedEBParameter(consumes, parameterResult, p, i, tmp); } i++; } return parameterResult; }
Example 4
Source File: EndpointValidator.java From msf4j with Apache License 2.0 | 6 votes |
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 5
Source File: ServiceVerticle.java From vert.x-microservice with Apache License 2.0 | 6 votes |
private Object[] invokeWSParameters(Message<byte[]> m, Method method) { final WSDataWrapper wrapper = getWSDataWrapper(m); final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); int i = 0; for (java.lang.reflect.Parameter p : parameters) { if (p.getType().equals(WSMessageReply.class)) { parameterResult[i] = new WSMessageReply(wrapper.getEndpoint(), this.vertx.eventBus(), this.getConfig()); } else { putTypedWSParameter(consumes, parameterResult, p, i, wrapper.getData()); } i++; } return parameterResult; }
Example 6
Source File: AnnotationProcessor.java From rest.vertx with Apache License 2.0 | 6 votes |
/** * Helper to convert class/method to String for reporting purposes * * @param clazz holding method * @param method method in class * @return class.method(type arg0, type arg1 .. type argN) */ private static String getClassMethod(Class<?> clazz, Method method) { StringBuilder builder = new StringBuilder(); builder.append(clazz.getName()).append(".").append(method.getName()); builder.append("("); if (method.getParameterCount() > 0) { for (int i = 0; i < method.getParameterCount(); i++) { Parameter param = method.getParameters()[i]; builder.append(param.getType().getSimpleName()).append(" ").append(param.getName()); if (i + 1 < method.getParameterCount()) { builder.append(", "); } } } builder.append(")"); return builder.toString(); }
Example 7
Source File: AbstractMetricsAdvice.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * Production unique name based on method name * * @param invocation * @return */ protected String getMetricName(MethodInvocation invocation) { String metricName = methodSignCache.get(invocation.getMethod()); if (metricName == null) { Method m = invocation.getMethod(); StringBuffer sign = new StringBuffer(this.classNameForShort(invocation.getThis().getClass().getName())); sign.append("."); sign.append(m.getName()); sign.append("("); Parameter[] params = m.getParameters(); if (params != null) { for (Parameter p : params) { sign.append(this.paramTypeForShort(p.getType().getSimpleName())); sign.append(" "); sign.append(p.getName()); sign.append(","); } if (sign.length() > 1) { sign.delete(sign.length() - 1, sign.length()); } sign.append(")"); } methodSignCache.put(m, metricName = sign.toString()); } return metricName; }
Example 8
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 9
Source File: Methods.java From raistlic-lib-commons-core with Apache License 2.0 | 5 votes |
@Override public boolean test(Method method) { if (method == null) { return false; } for (Parameter parameter : method.getParameters()) { if (!parameter.isAnnotationPresent(annotationType)) { return false; } } return true; }
Example 10
Source File: ObjectUtil.java From mybatis-generator-plugin with Apache License 2.0 | 5 votes |
/** * 执行方法(mapper动态代理后VarArgs检查有问题) * @param methodName * @param args * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public Object invoke(String methodName, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { List<Method> methods = getMethods(methodName); for (Method method : methods) { if (method.getParameters().length == 1 && args == null) { method.setAccessible(true); return method.invoke(this.object, new Object[]{null}); } else if (method.getParameterTypes().length == args.length) { boolean flag = true; Class[] parameterTypes = method.getParameterTypes(); // !! mapper动态代理后VarArgs检查有问题 // 暂时只检查前几位相同就假设为可变参数 int check = parameterTypes.length > 0 ? parameterTypes.length - (parameterTypes[parameterTypes.length - 1].getName().startsWith("[") ? 1 : 0) : 0; for (int i = 0; i < check; i++) { Class parameterType = parameterTypes[i]; if (args[i] != null && !(parameterType.isAssignableFrom(args[i].getClass()))) { flag = false; } // 基础类型 if (parameterType.isPrimitive()) { switch (parameterType.getTypeName()) { case "boolean": flag = args[i] instanceof Boolean; break; default: flag = false; } } } if (flag) { method.setAccessible(true); return method.invoke(this.object, args); } } } throw new NoSuchMethodError("没有找到方法:" + methodName); }
Example 11
Source File: CommandInvocationHandler.java From chrome-devtools-java-client with Apache License 2.0 | 5 votes |
/** * Builds method params given a method and its args. * * @param method Method. * @param args Method args. * @return Map of params. */ private Map<String, Object> buildMethodParams(Method method, Object[] args) { Map<String, Object> params = new HashMap<>(); Parameter[] parameters = method.getParameters(); if (args != null) { for (int i = 0; i < args.length; i++) { params.put(parameters[i].getAnnotation(ParamName.class).value(), args[i]); } } return params; }
Example 12
Source File: BadClassFiles.java From jdk8u-jdk 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 13
Source File: CompiledClassUtils.java From Concurnas with MIT License | 5 votes |
private static HashSet<MethodHolder> getAllMethods(Class<?> cls) { HashSet<MethodHolder> ret; if(classToMethodCache.containsKey(cls)) { return classToMethodCache.get(cls); }else { ret = new HashSet<MethodHolder>(); //System.err.println("get all methods for: " + cls); for(Method m : cls.getDeclaredMethods()){ if(!m.isBridge()){ Parameter[] params = m.getParameters(); if(params.length > 0) { Parameter param = params[params.length-1]; if(param.getParameterizedType().equals(Fiber.class)) { continue;//skip all instances which have bee fiberized } } ret.add(new MethodHolder(m)); } } if(cls.equals(com.concurnas.lang.Actor.class)) { ret.addAll(basicObjectMethods); } else if(cls.isInterface()){ //add all the basic object methods as well ret.addAll(basicObjectMethods); } classToMethodCache.put(cls, ret); } return ret; }
Example 14
Source File: AbstractGrpcFactory.java From joyrpc with Apache License 2.0 | 5 votes |
/** * 构建请求包装类型 * * @param clz 类 * @param method 方法 * @param naming 方法名提供者 * @return 包装的类 * @throws Exception 异常 */ protected ClassWrapper getRequestWrapper(final Class<?> clz, final Method method, final Naming naming) throws Exception { Parameter[] parameters = method.getParameters(); switch (parameters.length) { case 0: return null; case 1: Class<?> clazz = parameters[0].getType(); if (isPojo(clazz)) { return new ClassWrapper(clazz, false); } default: return new ClassWrapper(buildRequestClass(clz, method, naming), true); } }
Example 15
Source File: ParameterArgs.java From concursus with MIT License | 5 votes |
public static ParameterArgs forMethod(Method method, int skip) { checkNotNull(method, "method must not be null"); checkArgument(method.getParameterCount() >= skip, "method %s must have at least %s arguments", method, skip); Parameter[] parameters = method.getParameters(); String[] names = Stream.of(parameters).skip(skip).map(ParameterArgs::getParameterName).toArray(String[]::new); Type[] types = Stream.of(method.getGenericParameterTypes()).skip(skip).toArray(Type[]::new); Map<String, Type> typesByName = IntStream.range(0, names.length) .collect(HashMap::new, (m, i) -> m.put(names[i], types[i]), null); return new ParameterArgs(names, typesByName); }
Example 16
Source File: FlowerServiceUtil.java From flower with Apache License 2.0 | 5 votes |
public static Method getProcessMethod(Class<?> clazz) { if (clazz == null) { return null; } Method[] methods = clazz.getMethods(); if (methods == null) { return null; } Method paramIsObjectMethod = null; Method result = null; for (int i = methods.length; i > 0; i--) { Method method = methods[i - 1]; if ("process".equals(method.getName()) && method.getParameterCount() == 2) { Parameter param = method.getParameters()[0]; Parameter pa = method.getParameters()[1]; if (pa.getType().equals(ServiceContext.class)) { if (param.getType().equals(Object.class)) { paramIsObjectMethod = method; } else { result = method; } } } } if (result != null) { return result; } return paramIsObjectMethod; }
Example 17
Source File: LegalEnumRule.java From BlogManagePlatform with Apache License 2.0 | 5 votes |
@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 18
Source File: OutVertexMethodHandler.java From Ferma with Apache License 2.0 | 5 votes |
@Override public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) { final java.lang.reflect.Parameter[] arguments = method.getParameters(); if (ReflectionUtility.isGetMethod(method)) if (arguments == null || arguments.length == 0) return this.getNode(builder, method, annotation); else throw new IllegalStateException(method.getName() + " was annotated with @OutVertex but had arguments."); else throw new IllegalStateException(method.getName() + " was annotated with @OutVertex but did not begin with: get"); }
Example 19
Source File: TypeUtilTest.java From fastquery with Apache License 2.0 | 4 votes |
@Test public void findAnnotationIndex() throws NoSuchMethodException, SecurityException { Method method = TypeUtilTest.class.getMethod("todo", Integer.class, Integer.class); Parameter[] parameters = method.getParameters(); assertThat(TypeUtil.findAnnotationIndex(Id.class, parameters), is(0)); }
Example 20
Source File: DefaultTokenProviderSupport.java From tomato with Apache License 2.0 | 4 votes |
@Override public String findTomatoToken(Method method, Object[] args) throws Exception { Parameter[] parameters = method.getParameters(); for (int i = 0; i < method.getParameterCount(); i++) { Parameter parameter = parameters[i]; Object arg = args[i]; if (arg == null) continue; AbstractTokenProvider.ParameterType parameterType = typeArgParameter(arg); TomatoToken tomatoToken = findTomatoToken(parameter); if (tomatoToken == null) continue; String tokenName = tomatoToken.value(); switch (parameterType) { case HTTP_REQUEST: return ((HttpServletRequest) arg).getParameter(tokenName); case OBJECT: Class<?> argClass = arg.getClass(); Field field = classFieldCache.get(argClass); if (field == null) { field = ReflectionUtils.findField(argClass, tokenName); if (field == null) { String errorMsg = String.format("Don't find %s in %s", tokenName, argClass); throw new RuntimeException(errorMsg); } if (!field.isAccessible()) { field.setAccessible(true); } classFieldCache.put(argClass, field); } Object tokenFieldValue = field.get(arg); if (tokenFieldValue == null) continue; if (!BaseTypeTools.isBaseType(tokenFieldValue.getClass(), true)) { //如果不是基本类型错误提示 throw new RuntimeException("Token may be base type,not is object type"); } return String.valueOf(tokenFieldValue); case BASE_TYPE: return String.valueOf(arg); default: break; } } return null; }