List of usage examples for java.lang.reflect Method getParameterCount
public int getParameterCount()
From source file:edu.asu.ser.jsonrpc.lite.server.AbstractServer.java
/** * Returns the method object by matching names with all class methods of user's server implementation * @param name : method to find//from ww w. java 2s .co m * @param params : method params in JSON format from Request * @param ob : object of class which has actual implementation of RPC method * @return method : method object referencing the method in the class * @throws JsonRpcException */ private Method getMethodByName(String name, Object ob, JSONArray params) throws JsonRpcException { Method[] allMethods = ob.getClass().getMethods(); boolean flag = false; boolean methodExists = false; Method found = null; for (Method method : allMethods) { if (method.getName().equals(name) && method.getParameterCount() == params.length()) { methodExists = true; if (checkParamsMatch(method, params)) { flag = true; found = method; break; } } } if (flag) return found; if (!methodExists) throw new JsonRpcException(RPCError.METHOD_NOT_FOUND_ERROR); else throw new JsonRpcException(RPCError.INVALID_PARAMS_ERROR); }
From source file:com.haulmont.cuba.web.gui.components.table.LinkCellClickListener.java
protected Method findLinkInvokeMethod(Class cls, String methodName) { Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, new Class[] { Entity.class, String.class }); if (exactMethod != null) { return exactMethod; }/* www . j a v a2 s .c o m*/ // search through all methods Method[] methods = cls.getMethods(); for (Method availableMethod : methods) { if (availableMethod.getName().equals(methodName)) { if (availableMethod.getParameterCount() == 2 && Void.TYPE.equals(availableMethod.getReturnType())) { if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0]) && String.class == availableMethod.getParameterTypes()[1]) { // get accessible version of method return MethodUtils.getAccessibleMethod(availableMethod); } } } } return null; }
From source file:com.epam.catgenome.manager.externaldb.bindings.ExternalDBBindingTest.java
private void processFactory(Object factory) throws InvocationTargetException, IllegalAccessException, InstantiationException { List<Object> factoryObjects = new ArrayList<>(); Map<Class, Object> objectMap = new HashMap<>(); for (Method m : factory.getClass().getDeclaredMethods()) { if (Modifier.isPublic(m.getModifiers())) { Object o;//w w w .java 2 s .c o m if (m.getParameterCount() == 0) { o = m.invoke(factory); } else { Object[] params = new Object[m.getParameterCount()]; for (int i = 0; i < m.getParameterCount(); i++) { params[i] = createParam(m.getParameterTypes()[i]); } o = m.invoke(factory, params); } factoryObjects.add(o); objectMap.put(o.getClass(), o); } } for (Object o : factoryObjects) { for (Method m : o.getClass().getDeclaredMethods()) { if (Modifier.isPublic(m.getModifiers())) { if (m.getParameterTypes().length > 0) { Class type = m.getParameterTypes()[0]; if (objectMap.containsKey(type)) { m.invoke(o, objectMap.get(type)); } else { Object param = createParam(type); m.invoke(o, param); } } else { m.invoke(o); } } } } }
From source file:de.jackwhite20.japs.client.sub.impl.SubscriberImpl.java
@Override public void subscribeMulti(Class<?> handler) { // Get channel and check the class for annotation etc. String channel = getChannelFromAnnotation(handler); try {//from ww w . j a va 2s. c o m List<MultiHandlerInfo.Entry> entries = new ArrayList<>(); Object object = handler.newInstance(); for (Method method : object.getClass().getDeclaredMethods()) { if (method.getParameterCount() == 1) { if (method.isAnnotationPresent(Key.class) && method.isAnnotationPresent(Value.class)) { entries.add(new MultiHandlerInfo.Entry(method.getAnnotation(Key.class), method.getAnnotation(Value.class), method.getParameterTypes()[0], (method.getParameterTypes()[0].getSimpleName().equals("JSONObject")) ? ClassType.JSON : ClassType.GSON, method)); } } } multiHandlers.put(channel, new MultiHandlerInfo(entries, object)); JSONObject jsonObject = new JSONObject().put("op", OpCode.OP_REGISTER_CHANNEL.getCode()).put("ch", channel); write(jsonObject, false); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.springframework.cloud.stream.reactive.StreamEmitterAnnotationBeanPostProcessor.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private void invokeSetupMethodOnToTargetChannel(Method method, Object bean, String outboundName) { Object[] arguments = new Object[method.getParameterCount()]; Object targetBean = null;/*from w w w. ja va2s . c o m*/ for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) { MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex); Class<?> parameterType = methodParameter.getParameterType(); Object targetReferenceValue = null; if (methodParameter.hasParameterAnnotation(Output.class)) { targetReferenceValue = AnnotationUtils .getValue(methodParameter.getParameterAnnotation(Output.class)); } else if (arguments.length == 1 && StringUtils.hasText(outboundName)) { targetReferenceValue = outboundName; } if (targetReferenceValue != null) { targetBean = this.applicationContext.getBean((String) targetReferenceValue); for (StreamListenerParameterAdapter<?, Object> streamListenerParameterAdapter : this.streamListenerParameterAdapters) { if (streamListenerParameterAdapter.supports(targetBean.getClass(), methodParameter)) { arguments[parameterIndex] = streamListenerParameterAdapter.adapt(targetBean, methodParameter); if (arguments[parameterIndex] instanceof FluxSender) { closeableFluxResources.add((FluxSender) arguments[parameterIndex]); } break; } } Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of " + method + "from " + targetBean.getClass() + " to " + parameterType); } else { throw new IllegalStateException(StreamEmitterErrorMessages.ATLEAST_ONE_OUTPUT); } } Object result; try { result = method.invoke(bean, arguments); } catch (Exception e) { throw new BeanInitializationException("Cannot setup StreamEmitter for " + method, e); } if (!Void.TYPE.equals(method.getReturnType())) { if (targetBean == null) { targetBean = this.applicationContext.getBean(outboundName); } boolean streamListenerResultAdapterFound = false; for (StreamListenerResultAdapter streamListenerResultAdapter : this.streamListenerResultAdapters) { if (streamListenerResultAdapter.supports(result.getClass(), targetBean.getClass())) { Closeable fluxDisposable = streamListenerResultAdapter.adapt(result, targetBean); closeableFluxResources.add(fluxDisposable); streamListenerResultAdapterFound = true; break; } } Assert.state(streamListenerResultAdapterFound, StreamEmitterErrorMessages.CANNOT_CONVERT_RETURN_TYPE_TO_ANY_AVAILABLE_RESULT_ADAPTERS); } }
From source file:org.springframework.beans.GenericTypeAwarePropertyDescriptor.java
public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName, @Nullable Method readMethod, @Nullable Method writeMethod, Class<?> propertyEditorClass) throws IntrospectionException { super(propertyName, null, null); this.beanClass = beanClass; Method readMethodToUse = (readMethod != null ? BridgeMethodResolver.findBridgedMethod(readMethod) : null); Method writeMethodToUse = (writeMethod != null ? BridgeMethodResolver.findBridgedMethod(writeMethod) : null);/*from w w w.j a v a2s .c o m*/ if (writeMethodToUse == null && readMethodToUse != null) { // Fallback: Original JavaBeans introspection might not have found matching setter // method due to lack of bridge method resolution, in case of the getter using a // covariant return type whereas the setter is defined for the concrete property type. Method candidate = ClassUtils.getMethodIfAvailable(this.beanClass, "set" + StringUtils.capitalize(getName()), (Class<?>[]) null); if (candidate != null && candidate.getParameterCount() == 1) { writeMethodToUse = candidate; } } this.readMethod = readMethodToUse; this.writeMethod = writeMethodToUse; if (this.writeMethod != null) { if (this.readMethod == null) { // Write method not matched against read method: potentially ambiguous through // several overloaded variants, in which case an arbitrary winner has been chosen // by the JDK's JavaBeans Introspector... Set<Method> ambiguousCandidates = new HashSet<>(); for (Method method : beanClass.getMethods()) { if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse) && !method.isBridge() && method.getParameterCount() == writeMethodToUse.getParameterCount()) { ambiguousCandidates.add(method); } } if (!ambiguousCandidates.isEmpty()) { this.ambiguousWriteMethods = ambiguousCandidates; } } this.writeMethodParameter = new MethodParameter(this.writeMethod, 0); GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass); } if (this.readMethod != null) { this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass); } else if (this.writeMethodParameter != null) { this.propertyType = this.writeMethodParameter.getParameterType(); } this.propertyEditorClass = propertyEditorClass; }
From source file:koper.aop.AbstractSendMessageAdvice.java
/** * methodName ??/*from w w w . jav a 2s .c om*/ * @param clazz * @param methodName * @param argCount * @return * @throws NoSuchMethodException */ protected Method getMethodFromClass(Class<?> clazz, String methodName, int argCount) throws NoSuchMethodException { Method[] methods = clazz.getMethods(); for (Method method0 : methods) { String methodName0 = method0.getName(); if (methodName0.equals(methodName) && method0.getParameterCount() == argCount) { return method0; } } return null; }
From source file:org.apache.tinkerpop.gremlin.jsr223.JavaTranslator.java
private Object invokeMethod(final Object delegate, final Class returnType, final String methodName, final Object... arguments) { // populate method cache for fast access to methods in subsequent calls final Map<String, List<Method>> methodCache = GLOBAL_METHOD_CACHE.getOrDefault(delegate.getClass(), new HashMap<>()); if (methodCache.isEmpty()) buildMethodCache(delegate, methodCache); // create a copy of the argument array so as not to mutate the original bytecode final Object[] argumentsCopy = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { argumentsCopy[i] = translateObject(arguments[i]); }//from w ww . j a v a2 s . co m try { for (final Method method : methodCache.get(methodName)) { if (returnType.isAssignableFrom(method.getReturnType())) { if (method.getParameterCount() == argumentsCopy.length || (method.getParameterCount() > 0 && method.getParameters()[method.getParameters().length - 1].isVarArgs())) { final Parameter[] parameters = method.getParameters(); final Object[] newArguments = new Object[parameters.length]; boolean found = true; for (int i = 0; i < parameters.length; i++) { if (parameters[i].isVarArgs()) { final Class<?> parameterClass = parameters[i].getType().getComponentType(); if (argumentsCopy.length > i && !parameterClass.isAssignableFrom(argumentsCopy[i].getClass())) { found = false; break; } Object[] varArgs = (Object[]) Array.newInstance(parameterClass, argumentsCopy.length - i); int counter = 0; for (int j = i; j < argumentsCopy.length; j++) { varArgs[counter++] = argumentsCopy[j]; } newArguments[i] = varArgs; break; } else { if (i < argumentsCopy.length && (parameters[i].getType() .isAssignableFrom(argumentsCopy[i].getClass()) || (parameters[i].getType().isPrimitive() && (Number.class.isAssignableFrom(argumentsCopy[i].getClass()) || argumentsCopy[i].getClass().equals(Boolean.class) || argumentsCopy[i].getClass().equals(Byte.class) || argumentsCopy[i].getClass().equals(Character.class))))) { newArguments[i] = argumentsCopy[i]; } else { found = false; break; } } } if (found) { return 0 == newArguments.length ? method.invoke(delegate) : method.invoke(delegate, newArguments); } } } } } catch (final Throwable e) { throw new IllegalStateException( e.getMessage() + ":" + methodName + "(" + Arrays.toString(argumentsCopy) + ")", e); } throw new IllegalStateException("Could not locate method: " + delegate.getClass().getSimpleName() + "." + methodName + "(" + Arrays.toString(argumentsCopy) + ")"); }
From source file:org.springframework.context.event.ApplicationListenerMethodAdapter.java
private List<ResolvableType> resolveDeclaredEventTypes(Method method, @Nullable EventListener ann) { int count = method.getParameterCount(); if (count > 1) { throw new IllegalStateException( "Maximum one parameter is allowed for event listener method: " + method); }//from w w w. ja v a 2s.c o m if (ann != null && ann.classes().length > 0) { List<ResolvableType> types = new ArrayList<>(ann.classes().length); for (Class<?> eventType : ann.classes()) { types.add(ResolvableType.forClass(eventType)); } return types; } else { if (count == 0) { throw new IllegalStateException( "Event parameter is mandatory for event listener method: " + method); } return Collections.singletonList(ResolvableType.forMethodParameter(method, 0)); } }
From source file:com.linecorp.bot.spring.boot.support.LineMessageHandlerSupport.java
private HandlerMethod getMethodHandlerMethodFunction(Object consumer, Method method) { final EventMapping mapping = AnnotatedElementUtils.getMergedAnnotation(method, EventMapping.class); if (mapping == null) { return null; }//from w w w . j av a 2s. c om Preconditions.checkState(method.getParameterCount() == 1, "Number of parameter should be 1. But {}", (Object[]) method.getParameterTypes()); // TODO: Support more than 1 argument. Like MVC's argument resolver? final Type type = method.getGenericParameterTypes()[0]; final Predicate<Event> predicate = new EventPredicate(type); return new HandlerMethod(predicate, consumer, method, getPriority(mapping, type)); }