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

The following are Jave code examples for showing how to use getParameterCount() 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: 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 2
Project: Debuggery   File: ReflectionUtil.java   View Source Code Vote up 6 votes
/**
 * Gets the error message we should send when the input string is missing arguments
 *
 * @param method method with missing arguments
 * @return error message
 */
@Nonnull
public static String getArgMismatchString(Method method) {
    final String methodName = method.getName();
    final Class returnType = method.getReturnType();
    final String returnTypeName = returnType.getSimpleName();
    String returnInfo;

    if (returnType.equals(Void.TYPE)) {
        returnInfo = "returns void.";
    } else if (startsWithVowel.test(returnTypeName)) {
        returnInfo = "returns an " + returnTypeName;
    } else {
        returnInfo = "returns a " + returnTypeName;
    }

    return "Method " + methodName + " requires " + method.getParameterCount() + " args and " + returnInfo + "\n"
            + ReflectionUtil.getFormattedMethodSignature(method);
}
 
Example 3
Project: openjdk-jdk10   File: MethodSubstitutionPlugin.java   View Source Code Vote up 6 votes
/**
 * Determines if a given method is the substitute method of this plugin.
 */
private boolean isSubstitute(Method m) {
    if (Modifier.isStatic(m.getModifiers()) && m.getName().equals(name)) {
        if (parameters.length == m.getParameterCount()) {
            Class<?>[] mparams = m.getParameterTypes();
            int start = 0;
            if (!originalIsStatic) {
                start = 1;
                if (!mparams[0].isAssignableFrom(resolveType(parameters[0], false))) {
                    return false;
                }
            }
            for (int i = start; i < mparams.length; i++) {
                if (mparams[i] != resolveType(parameters[i], false)) {
                    return false;
                }
            }
            return true;
        }
    }
    return false;
}
 
Example 4
Project: hekate   File: RpcMethodInfo.java   View Source Code Vote up 6 votes
private static OptionalInt findAffinityArg(Method meth) {
    OptionalInt affinityArg = OptionalInt.empty();

    if (meth.getParameterCount() > 0) {
        for (int i = 0; i < meth.getParameterCount() && !affinityArg.isPresent(); i++) {
            Annotation[] annotations = meth.getParameterAnnotations()[i];

            for (int j = 0; j < annotations.length; j++) {
                if (RpcAffinityKey.class.isAssignableFrom(annotations[j].annotationType())) {
                    affinityArg = OptionalInt.of(i);

                    break;
                }
            }
        }
    }

    return affinityArg;
}
 
Example 5
Project: openjdk-jdk10   File: IntlTest.java   View Source Code Vote up 6 votes
protected IntlTest() {
    // Populate testMethods with all the test methods.
    Method[] methods = getClass().getDeclaredMethods();
    for (Method method : methods) {
        if (Modifier.isPublic(method.getModifiers())
            && method.getReturnType() == void.class
            && method.getParameterCount() == 0) {
            String name = method.getName();
            if (name.length() > 4) {
                if (name.startsWith("Test") || name.startsWith("test")) {
                    testMethods.put(name, method);
                }
            }
        }
    }
}
 
Example 6
Project: holon-vaadin   File: ViewNavigationUtils.java   View Source Code Vote up 6 votes
/**
 * Check given method has a valid signature for {@link OnShow} or {@link OnLeave} view method
 * @param viewClass View class
 * @param method Method to check
 * @param message Error message annotation description
 * @throws ViewConfigurationException Method is not valid
 */
private static void checkViewOnShowOrLeaveMethod(Class<?> viewClass, Method method, String message)
		throws ViewConfigurationException {
	if (method.getReturnType() != Void.class && method.getReturnType() != Void.TYPE) {
		throw new ViewConfigurationException("Invalid " + message + " method in view class " + viewClass.getName()
				+ ": method must be a void return method");
	}
	int params = method.getParameterCount();
	if (params > 1) {
		throw new ViewConfigurationException("Invalid " + message + " method in view class " + viewClass.getName()
				+ ": method must have no parameters or only one parameter of type ViewChangeEvent");
	}
	if (params == 1) {
		Parameter param = method.getParameters()[0];
		if (param.isVarArgs() || !(ViewChangeEvent.class.isAssignableFrom(param.getType())
				|| ViewNavigatorChangeEvent.class.isAssignableFrom(param.getType()))) {
			throw new ViewConfigurationException(
					"Invalid " + message + " method in view class " + viewClass.getName()
							+ ": method must have no parameters or only one parameter of type ViewChangeEvent");
		}
	}
}
 
Example 7
Project: camunda-bpm-swagger   File: ReturnTypeInfo.java   View Source Code Vote up 6 votes
@Override
public boolean test(final Method candidate) {
  final boolean result = original.getName().equals(candidate.getName()) // methods must have equal names
      && original.getParameterCount() == candidate.getParameterCount() // and same number of parameters
      && !original.getReturnType().equals(candidate.getReturnType()); // and different return types
  if (!result) {
    return false;
  }
  // check every parameter type
  for (int i = 0; i < original.getParameterCount(); i++) {
    if (!original.getParameterTypes()[i].equals(candidate.getParameterTypes()[i])) {
      // if parameter type are not matching, the implementation candidate is refused.
      return false;
    }
  }
  return true;
}
 
Example 8
Project: Debuggery   File: ReflectionChain.java   View Source Code Vote up 6 votes
private Object reflect(Object instance, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
    final int paramCount = method.getParameterCount();

    if (args.length != paramCount) {
        return ReflectionUtil.getArgMismatchString(method);
    }

    if (!method.isAccessible()) {
        method.setAccessible(true);
    }

    Object result;
    if (paramCount == 0) {
        result = method.invoke(instance);
    } else {
        result = method.invoke(instance, args);
    }

    return result;
}
 
Example 9
Project: holon-vaadin7   File: ViewNavigationUtils.java   View Source Code Vote up 6 votes
/**
 * Fire {@link OnShow} view methods
 * @param view View instance (not null)
 * @param configuration View configuration (not null)
 * @param event View change event
 * @param refresh <code>true</code> if is a page refresh
 * @throws ViewConfigurationException Error invoking view methods
 */
public static <E extends ViewChangeEvent & ViewNavigatorChangeEvent> void fireViewOnShow(View view,
		ViewConfiguration configuration, E event, boolean refresh) throws ViewConfigurationException {
	if (view == null) {
		throw new ViewConfigurationException("Null view instance");
	}
	if (configuration == null) {
		throw new ViewConfigurationException("Missing view configuration");
	}

	for (Method method : configuration.getOnShowMethods()) {
		if (!refresh || configuration.isFireOnRefresh(method)) {
			try {
				if (method.getParameterCount() == 0) {
					method.invoke(view, new Object[0]);
				} else {
					method.invoke(view, new Object[] { event });
				}
			} catch (Exception e) {
				throw new ViewConfigurationException("Failed to fire OnShow method " + method.getName()
						+ " on view class " + view.getClass().getName(), e);
			}
		}
	}
}
 
Example 10
Project: comdor   File: DisconnectedTestCase.java   View Source Code Vote up 5 votes
/**
 * All the methods of Disconnect should throw ISE.
 * @throws Exception If something goes wrong.
 */
@Test
public void allMethodsThrowISE() throws Exception {
    for(final Method method : Disconnected.class.getDeclaredMethods()) {
        try {
            if(!method.isAccessible()) {
                continue;
            }
            Object[] params = new Object[method.getParameterCount()];
            for(int i=0; i < method.getParameters().length; i++) {
                if(method.getParameters()[i].getType().equals(int.class)) {
                    params[i] = 0;
                } else if(method.getParameters()[i].getType().equals(boolean.class)) {
                    params[i] = false;
                } else {
                    params[i] = null;   
                }
            }
            method.invoke(new Disconnected(), params);
            Assert.fail("ISE should have been thrown by now!");
        } catch (final InvocationTargetException ex) {
            MatcherAssert.assertThat(
                ex.getCause().getMessage(),
                Matchers.equalTo(
                    "Not connected. Don't forget to "
                    + "get a connected instance by calling #connect()"
                )
            );
        }
    }
}
 
Example 11
Project: spring-tg   File: TgActionRegisterer.java   View Source Code Vote up 5 votes
private void checkTgPrePostActionMethod(Method preOrPostActionMethod) {

        if (preOrPostActionMethod.getParameterCount() != 0)
            throw new IllegalStateException(String.format("Pre and Post method parameters must be empty. Method: %s.%s",
                    preOrPostActionMethod.getDeclaringClass().getName(),
                    preOrPostActionMethod.getName())
            );

    }
 
Example 12
Project: promagent   File: Delegator.java   View Source Code Vote up 5 votes
private static boolean methodNameAndNumArgsMatch(Method interceptedMethod, HookMetadata.MethodSignature instrumentedMethod) {
    if (!interceptedMethod.getName().equals(instrumentedMethod.getMethodName())) {
        return false;
    }
    if (interceptedMethod.getParameterCount() != instrumentedMethod.getParameterTypes().size()) {
        return false;
    }
    return true;
}
 
Example 13
Project: OpenJSharp   File: NashornBeansLinker.java   View Source Code Vote up 5 votes
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final Object self = linkRequest.getReceiver();
    final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
    if (self instanceof ConsString) {
        // In order to treat ConsString like a java.lang.String we need a link request with a string receiver.
        final Object[] arguments = linkRequest.getArguments();
        arguments[0] = "";
        final LinkRequest forgedLinkRequest = linkRequest.replaceArguments(desc, arguments);
        final GuardedInvocation invocation = getGuardedInvocation(beansLinker, forgedLinkRequest, linkerServices);
        // If an invocation is found we add a filter that makes it work for both Strings and ConsStrings.
        return invocation == null ? null : invocation.filterArguments(0, FILTER_CONSSTRING);
    }

    if (self != null && "call".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        // Support dyn:call on any object that supports some @FunctionalInterface
        // annotated interface. This way Java method, constructor references or
        // implementations of java.util.function.* interfaces can be called as though
        // those are script functions.
        final Method m = getFunctionalInterfaceMethod(self.getClass());
        if (m != null) {
            final MethodType callType = desc.getMethodType();
            // 'callee' and 'thiz' passed from script + actual arguments
            if (callType.parameterCount() != m.getParameterCount() + 2) {
                throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self));
            }
            return new GuardedInvocation(
                    // drop 'thiz' passed from the script.
                    MH.dropArguments(desc.getLookup().unreflect(m), 1, callType.parameterType(1)),
                    Guards.getInstanceOfGuard(m.getDeclaringClass())).asTypeSafeReturn(
                            new NashornBeansLinkerServices(linkerServices), callType);
        }
    }
    return getGuardedInvocation(beansLinker, linkRequest, linkerServices);
}
 
Example 14
Project: flux-capacitor-client   File: HandlerInspector.java   View Source Code Vote up 5 votes
private static <M> List<Function<M, Object>> getParameterSuppliers(Method method,
                                                                   List<ParameterResolver<M>> resolvers) {
    if (method.getParameterCount() == 0) {
        throw new IllegalStateException("Annotated method should contain at least one parameter");
    }
    return Arrays.stream(method.getParameters())
            .map(p -> resolvers.stream().map(r -> r.resolve(p)).filter(Objects::nonNull).findFirst()
                    .orElseThrow(() -> new IllegalStateException("Could not resolve parameter " + p)))
            .collect(toList());
}
 
Example 15
Project: MystiCraft   File: CommandManager.java   View Source Code Vote up 5 votes
public void register(Class<?> c) {
	for (Method m : c.getMethods()) {
		if (Modifier.isStatic(m.getModifiers()) && m.getParameterCount() == 1
				&& m.getParameterTypes()[0] == CommandContext.class) {
			if (m.isAnnotationPresent(Command.class) && m.getReturnType() == boolean.class) {
				registerCommand(m, null);
			} else if (m.isAnnotationPresent(Completer.class) && m.getReturnType() == List.class) {
				registerCompleter(m, null);
			}
		}
	}
}
 
Example 16
Project: jdk8u-jdk   File: RemoteObjectInvocationHandler.java   View Source Code Vote up 4 votes
/**
 * Processes a method invocation made on the encapsulating
 * proxy instance, <code>proxy</code>, and returns the result.
 *
 * <p><code>RemoteObjectInvocationHandler</code> implements this method
 * as follows:
 *
 * <p>If <code>method</code> is one of the following methods, it
 * is processed as described below:
 *
 * <ul>
 *
 * <li>{@link Object#hashCode Object.hashCode}: Returns the hash
 * code value for the proxy.
 *
 * <li>{@link Object#equals Object.equals}: Returns <code>true</code>
 * if the argument (<code>args[0]</code>) is an instance of a dynamic
 * proxy class and this invocation handler is equal to the invocation
 * handler of that argument, and returns <code>false</code> otherwise.
 *
 * <li>{@link Object#toString Object.toString}: Returns a string
 * representation of the proxy.
 * </ul>
 *
 * <p>Otherwise, a remote call is made as follows:
 *
 * <ul>
 * <li>If <code>proxy</code> is not an instance of the interface
 * {@link Remote}, then an {@link IllegalArgumentException} is thrown.
 *
 * <li>Otherwise, the {@link RemoteRef#invoke invoke} method is invoked
 * on this invocation handler's <code>RemoteRef</code>, passing
 * <code>proxy</code>, <code>method</code>, <code>args</code>, and the
 * method hash (defined in section 8.3 of the "Java Remote Method
 * Invocation (RMI) Specification") for <code>method</code>, and the
 * result is returned.
 *
 * <li>If an exception is thrown by <code>RemoteRef.invoke</code> and
 * that exception is a checked exception that is not assignable to any
 * exception in the <code>throws</code> clause of the method
 * implemented by the <code>proxy</code>'s class, then that exception
 * is wrapped in an {@link UnexpectedException} and the wrapped
 * exception is thrown.  Otherwise, the exception thrown by
 * <code>invoke</code> is thrown by this method.
 * </ul>
 *
 * <p>The semantics of this method are unspecified if the
 * arguments could not have been produced by an instance of some
 * valid dynamic proxy class containing this invocation handler.
 *
 * @param proxy the proxy instance that the method was invoked on
 * @param method the <code>Method</code> instance corresponding to the
 * interface method invoked on the proxy instance
 * @param args an array of objects containing the values of the
 * arguments passed in the method invocation on the proxy instance, or
 * <code>null</code> if the method takes no arguments
 * @return the value to return from the method invocation on the proxy
 * instance
 * @throws  Throwable the exception to throw from the method invocation
 * on the proxy instance
 **/
public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable
{
    if (! Proxy.isProxyClass(proxy.getClass())) {
        throw new IllegalArgumentException("not a proxy");
    }

    if (Proxy.getInvocationHandler(proxy) != this) {
        throw new IllegalArgumentException("handler mismatch");
    }

    if (method.getDeclaringClass() == Object.class) {
        return invokeObjectMethod(proxy, method, args);
    } else if ("finalize".equals(method.getName()) && method.getParameterCount() == 0 &&
        !allowFinalizeInvocation) {
        return null; // ignore
    } else {
        return invokeRemoteMethod(proxy, method, args);
    }
}
 
Example 17
Project: smart-testing   File: SurefireProviderLoggerFactory.java   View Source Code Vote up 4 votes
private boolean isPublicConsoleLogMethod(Method method){
    return method.getParameterCount() == 1
        && method.getParameterTypes()[0] == String.class
        && method.getModifiers() == Modifier.PUBLIC;
}
 
Example 18
Project: ETF-Java   File: ReflectionUtils.java   View Source Code Vote up 4 votes
public PropertyManager(Object instance, Field field) {
	this.instance = instance;
	field.setAccessible(true);
	IPropertyAccessor accessor = null;
	boolean isFinal = Modifier.isFinal(field.getModifiers());
	IPropertyMutator mutator = isFinal ? NOPAccessorAndMutator.INSTANCE : null;
	for (Method m : getAllMethods(instance.getClass())) {
		if (mutator != null && accessor != null)
			break;
		
		m.setAccessible(true);
		
		if (m.getName().equals(String.format("get%s", capitalize(field.getName())))) {
			accessor = new MethodAccessorAndMutator(instance, m);
			continue;
		} else if (!isFinal
				&& m.getName().equals(String.format("set%s", capitalize(field.getName())))
				&& m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(field.getType())) {
			mutator = new MethodAccessorAndMutator(instance, m);
			continue;
		} else if (m.getDeclaredAnnotation(GetterMethod.class) != null) {
			if (m.getDeclaredAnnotation(GetterMethod.class).value().equals(field.getName())) {
				accessor = new MethodAccessorAndMutator(instance, m);
				continue;
			}
		} else if (!isFinal && m.getDeclaredAnnotation(SetterMethod.class) != null
				&& m.getParameterCount() == 1) {
			if (m.getDeclaredAnnotation(SetterMethod.class).value().equals(field.getName())) {
				mutator = new MethodAccessorAndMutator(instance, m);
				continue;
			}
		}
	}
	
	if (accessor == null)
		accessor = new FieldAccessorAndMutator(instance, field);
	
	if (mutator == null)
		mutator = new FieldAccessorAndMutator(instance, field);
	
	this.accessor = accessor;
	this.mutator = mutator;
	
	this.name = field.getName();
}
 
Example 19
Project: cryptotrader   File: PipelineImpl.java   View Source Code Vote up 3 votes
@VisibleForTesting
Request validateRequest(Request request) {

    for (Method m : Request.class.getMethods()) {

        if (!m.getName().startsWith("get")) {
            continue;
        }

        if (m.getParameterCount() != 0) {
            continue;
        }

        try {

            Object value = m.invoke(request);

            Objects.requireNonNull(value);

        } catch (Exception e) {

            log.warn("Invalid Request : " + m.getName());

            return null;

        }

    }

    return request;

}
 
Example 20
Project: spark-project   File: ReflectionUtils.java   View Source Code Vote up 2 votes
/**
 * Determine whether the given method is a "hashCode" method.
 * @see java.lang.Object#hashCode()
 */
public static boolean isHashCodeMethod(Method method) {
	return (method != null && method.getName().equals("hashCode") && method.getParameterCount() == 0);
}