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

The following examples show how to use java.lang.reflect.Method#getParameterCount() . These examples are extracted from open source projects. 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
@Nullable
private Method getFinder(Class<?> entityClass) {
	String finderMethod = "find" + getEntityName(entityClass);
	Method[] methods;
	boolean localOnlyFiltered;
	try {
		methods = entityClass.getDeclaredMethods();
		localOnlyFiltered = true;
	}
	catch (SecurityException ex) {
		// Not allowed to access non-public methods...
		// Fallback: check locally declared public methods only.
		methods = entityClass.getMethods();
		localOnlyFiltered = false;
	}
	for (Method method : methods) {
		if (Modifier.isStatic(method.getModifiers()) && method.getName().equals(finderMethod) &&
				method.getParameterCount() == 1 && method.getReturnType().equals(entityClass) &&
				(localOnlyFiltered || method.getDeclaringClass().equals(entityClass))) {
			return method;
		}
	}
	return null;
}
 
Example 2
Source Project: cuba   File: LinkCellClickListener.java    License: Apache License 2.0 6 votes vote down vote up
protected Method findLinkInvokeMethod(Class cls, String methodName) {
    Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, Entity.class, String.class);
    if (exactMethod != null) {
        return exactMethod;
    }

    // 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;
}
 
Example 3
Source Project: java-technology-stack   File: ReplaceOverride.java    License: MIT License 6 votes vote down vote up
@Override
public boolean matches(Method method) {
	if (!method.getName().equals(getMethodName())) {
		return false;
	}
	if (!isOverloaded()) {
		// Not overloaded: don't worry about arg type matching...
		return true;
	}
	// If we get here, we need to insist on precise argument matching...
	if (this.typeIdentifiers.size() != method.getParameterCount()) {
		return false;
	}
	Class<?>[] parameterTypes = method.getParameterTypes();
	for (int i = 0; i < this.typeIdentifiers.size(); i++) {
		String identifier = this.typeIdentifiers.get(i);
		if (!parameterTypes[i].getName().contains(identifier)) {
			return false;
		}
	}
	return true;
}
 
Example 4
private String getColumnValueFromMethod(Method method, Object object) {
    Object columnValue = null;
    try {
        if (!method.isAccessible()) {
            method.setAccessible(true);
            if (method.getParameterCount() == 0) {
                columnValue = method.invoke(object);
            }
            method.setAccessible(false);
        } else {
            if (method.getParameterCount() == 0) {
                columnValue = method.invoke(object);
            }
        }
    } catch (IllegalAccessException | InvocationTargetException ignored) {
    	// do nothing
    }

    return columnValue != null ? columnValue.toString() : StringUtils.EMPTY;
}
 
Example 5
private static void testDestroy(KerberosTicket t) throws Exception {
    t.destroy();
    if (!t.isDestroyed()) {
        throw new RuntimeException("ticket should have been destroyed");
    }
    // Although these methods are meaningless, they can be called
    for (Method m: KerberosTicket.class.getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers())
                && m.getParameterCount() == 0) {
            System.out.println("Testing " + m.getName() + "...");
            try {
                m.invoke(t);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof RefreshFailedException ||
                        cause instanceof IllegalStateException) {
                    // this is OK
                } else {
                    throw e;
                }
            }
        }
    }
    System.out.println("Destroy Test Passed");
}
 
Example 6
Source Project: resilience4j   File: FallbackMethod.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean filter(Method method, MethodMeta methodMeta) {
    if (!method.getName().equals(methodMeta.fallbackMethodName)) {
        return false;
    }
    if (!methodMeta.returnType.isAssignableFrom(method.getReturnType())) {
        return false;
    }
    if (method.getParameterCount() == 1) {
        return Throwable.class.isAssignableFrom(method.getParameterTypes()[0]);
    }
    if (method.getParameterCount() != methodMeta.params.length + 1) {
        return false;
    }
    Class[] targetParams = method.getParameterTypes();
    for (int i = 0; i < methodMeta.params.length; i++) {
        if (methodMeta.params[i] != targetParams[i]) {
            return false;
        }
    }
    return Throwable.class.isAssignableFrom(targetParams[methodMeta.params.length]);
}
 
Example 7
static boolean isMetadataBuilder(Method method) {
    if (method.getParameterCount() != 1)
        return false;
    if (hasAnnotation(method, Meta.class))
        return true;
    if (hasAnnotation(method, Key.class))
        return false;
    Method correspondingGetter = getCorrespondingGetter(method);
    return hasAnnotation(correspondingGetter, Meta.class);
}
 
Example 8
Source Project: quarkus   File: QuarkusTestNgCallbacks.java    License: Apache License 2.0 5 votes vote down vote up
static void invokeTestNgAfterClasses(Object testInstance)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
    if (testInstance != null) {
        List<Method> afterClasses = new ArrayList<>();
        collectCallbacks(testInstance.getClass(), afterClasses, (Class<? extends Annotation>) testInstance.getClass()
                .getClassLoader().loadClass(AfterClass.class.getName()));
        for (Method m : afterClasses) {
            // we don't know the values for parameterized methods that TestNG allows, we just skip those
            if (m.getParameterCount() == 0) {
                m.setAccessible(true);
                m.invoke(testInstance);
            }
        }
    }
}
 
Example 9
Source Project: mangooio   File: DispatcherHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the method parameter of a mapped controller method to a map
 *
 * @return A Map containing the declared methods of the method parameters and their class type
 */
private Map<String, Class<?>> getMethodParameters() {
    final Map<String, Class<?>> parameters = new LinkedHashMap<>();
    for (final Method declaredMethod : this.controllerClass.getDeclaredMethods()) {
        if (declaredMethod.getName().equals(this.controllerMethodName) && declaredMethod.getParameterCount() > 0) {
            Arrays.stream(declaredMethod.getParameters()).forEach(parameter -> parameters.put(parameter.getName(), parameter.getType()));
            break;
        }
    }

    return parameters;
}
 
Example 10
/**
 * Returns whether the method is {@link Object#toString}.
 *
 * @param method the method to test.
 * @return <code>true</code> iff yes.
 */
private boolean isMethodToString(Method method) {
	// TODO: Move to utils.
	if (method == null)
		return false;

	if (method.getParameterCount() != 0)
		return false;
	if (!String.class.equals(method.getReturnType()))
		return false;
	return "toString".equals(method.getName());
}
 
Example 11
@SuppressWarnings("NestedMethodCall")
public OnMessageMethodInvoker(final Object bean, final Method method,
                              final List<NettyOnMessageParameterResolver> parameterResolvers,
                              final boolean sendResult) {

    final int parameterCount = method.getParameterCount();

    //noinspection NestedMethodCall
    final List<MethodParameter> messageBodyArgs = IntStream.range(0, parameterCount)
            .mapToObj(i -> new MethodParameter(method, i))
            .filter(mp -> mp.hasParameterAnnotation(NettyMessageBody.class))
            .collect(Collectors.toList());

    if (messageBodyArgs.size() > 1) {
        throw new IllegalArgumentException(method + " has more than one NettyMessageBody annotated parameters");
    }

    messageBodyType = Optional.ofNullable(
            messageBodyArgs.size() == 1 ? messageBodyArgs.get(0).getParameterType() : null
    )
            .map(c -> c.isPrimitive() ? Primitives.wrap(c) : c)
            .orElse(null);

    invoker = buildInvoker(Invoker.class, method, ONM_INVOKE_HANDLER, sendResult, (invokerInternalName, m, firstVarIdx) -> {
        final Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            m.visitIntInsn(ALOAD, 0);
            m.visitFieldInsn(GETFIELD, invokerInternalName, "resolvers", ONM_RESA_DESCRIPTOR);
            m.visitIntInsn(BIPUSH, i);
            m.visitInsn(AALOAD);
            m.visitIntInsn(ALOAD, 2);
            m.visitIntInsn(ALOAD, 3);
            m.visitMethodInsn(INVOKEINTERFACE, ONM_RES_INTERNAL_NAME, "resolve", ONM_RESOLVE_DESCRIPTOR, true);
            m.visitIntInsn(ASTORE, firstVarIdx + i);
        }
    });

    invoker.bean = bean;
    invoker.resolvers = parameterResolvers.toArray(new NettyOnMessageParameterResolver[0]);
}
 
Example 12
private boolean methodParameterSupports(Method method) {
	boolean supports = false;
	for (int i = 0; i < method.getParameterCount(); i++) {
		MethodParameter methodParameter = MethodParameter.forExecutable(method, i);
		Class<?> parameterType = methodParameter.getParameterType();
		if (parameterType.equals(KStream.class) || parameterType.equals(KTable.class)
				|| parameterType.equals(GlobalKTable.class)) {
			supports = true;
		}
	}
	return supports;
}
 
Example 13
Source Project: canon-sdk-java   File: CanonCameraMockTest.java    License: MIT License 5 votes vote down vote up
@Test
void sendAllGetCommands() throws InvocationTargetException, IllegalAccessException {
    final Method[] methods = cameraWithSerialNumber.getProperty().getClass().getMethods();
    int count = 0;
    for (final Method method : methods) {
        if (!method.getName().startsWith("get") || method.getName().equals("getClass")) {
            continue;
        }
        if (method.getParameterCount() > 0) {
            continue;
        }

        final CanonCommand command;
        try {
            command = (CanonCommand) method.invoke(cameraWithSerialNumber.getProperty());
        } catch (IllegalArgumentException | ClassCastException e) {
            log.warn("Fail: {}", method, e);
            throw e;
        }

        Assertions.assertNotNull(command);

        count++;

        verify(commandDispatcher).scheduleCommand(command);
        verify(commandDispatcher, times(count)).scheduleCommand(any());
    }

}
 
Example 14
Source Project: beihu-boot   File: SecurityManager.java    License: Apache License 2.0 5 votes vote down vote up
private Decryptor buildDecryptor(Object bean, Method method) {
    ReflectionUtils.makeAccessible(method);
    if (method.getParameterCount() == 1) {
        return new SingleMethodDecryptor(bean, method);
    } else {
        return new MultMethodDecryptor(bean, method);
    }
}
 
Example 15
Source Project: CheckPoint   File: ParameterMapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find method method.
 *
 * @param c          the c
 * @param methodName the method name
 * @return the method
 */
public static Method findMethod(Class<?> c, String methodName) {
    for (Method m : c.getMethods()) {
        if (!m.getName().equalsIgnoreCase(methodName)) {
            continue;
        }
        if (m.getParameterCount() != 1) {
            continue;
        }
        return m;
    }

    return null;
}
 
Example 16
Source Project: turbo-rpc   File: ReflectUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取字段的get方法
 * 
 * @param methods
 * @param field
 * @return
 */
public static Method getGetMethod(Method[] methods, Field field) {
	String name = field.getName();
	Class<?> fieldType = field.getType();

	String getMethodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);

	for (int i = 0; i < methods.length; i++) {
		Method method = methods[i];

		if (method.getParameterCount() > 0) {
			continue;
		}

		String methodName = method.getName();

		if (!methodName.equals(name) && !methodName.equals(getMethodName)) {
			continue;
		}

		if (!fieldType.isAssignableFrom(method.getReturnType())) {
			continue;
		}

		return method;
	}

	return null;
}
 
Example 17
/**
 * Returns whether the method is {@link Object#clone}.
 *
 * @param method the method to test.
 * @return <code>true</code> iff yes.
 */
private boolean isMethodClone(Method method) {
	// TODO: Move to utils.
	if (method == null)
		return false;

	if (method.getParameterCount() != 0)
		return false;
	if (!Object.class.equals(method.getReturnType()))
		return false;
	return "clone".equals(method.getName());
}
 
Example 18
protected final void addMethod(Type type, Method method, boolean allowReaders, boolean allowWriters)
{
    checkArgument(method.isAnnotationPresent(ThriftField.class));

    ThriftField annotation = method.getAnnotation(ThriftField.class);
    Class<?> clazz = TypeToken.of(type).getRawType();

    // verify parameters
    if (isValidateGetter(method)) {
        if (allowReaders) {
            MethodExtractor methodExtractor = new MethodExtractor(type, method, annotation, THRIFT_FIELD);
            fields.add(methodExtractor);
            extractors.add(methodExtractor);
        }
        else {
            metadataErrors.addError("Reader method %s.%s is not allowed on a builder class", clazz.getName(), method.getName());
        }
    }
    else if (isValidateSetter(method)) {
        if (allowWriters) {
            List<ParameterInjection> parameters;
            if ((method.getParameterCount() > 1) || hasThriftFieldAnnotation(method)) {
                parameters = getParameterInjections(
                        type,
                        method.getParameterAnnotations(),
                        resolveFieldTypes(type, method.getGenericParameterTypes()),
                        extractParameterNames(method));
                if (annotation.value() != Short.MIN_VALUE) {
                    metadataErrors.addError("A method with annotated parameters can not have a field id specified: %s.%s ", clazz.getName(), method.getName());
                }
                if (!annotation.name().isEmpty()) {
                    metadataErrors.addError("A method with annotated parameters can not have a field name specified: %s.%s ", clazz.getName(), method.getName());
                }
                if (annotation.requiredness() == Requiredness.REQUIRED) {
                    metadataErrors.addError("A method with annotated parameters can not be marked as required: %s.%s ", clazz.getName(), method.getName());
                }
            }
            else {
                Type parameterType = resolveFieldTypes(type, method.getGenericParameterTypes())[0];
                parameters = ImmutableList.of(new ParameterInjection(type, 0, annotation, ReflectionHelper.extractFieldName(method), parameterType));
            }
            fields.addAll(parameters);
            methodInjections.add(new MethodInjection(method, parameters));
        }
        else {
            metadataErrors.addError("Inject method %s.%s is not allowed on struct class, since struct has a builder", clazz.getName(), method.getName());
        }
    }
    else {
        metadataErrors.addError("Method %s.%s is not a supported getter or setter", clazz.getName(), method.getName());
    }
}
 
Example 19
Source Project: SikuliNG   File: SX.java    License: MIT License 4 votes vote down vote up
public static Map<String, String> listPublicMethods(Class clazz, boolean silent) {
  Method[] declaredMethods = clazz.getDeclaredMethods();
  Map<String, String> publicMethods = new HashMap<>();
  for (Method method : declaredMethods) {
    int modifiers = method.getModifiers();
    if (Modifier.isPublic(modifiers)) {
      int parameterCount = method.getParameterCount();
      Class<?>[] exceptionTypes = method.getExceptionTypes();
      String throwsException = "";
      if (exceptionTypes.length > 0) {
        throwsException = "x";
      }
      String name = method.getName();
      String prefix = "";
      if (name.startsWith("getAll")) {
        prefix = "getAll";
      } else if (name.startsWith("get")) {
        prefix = "get";
      } else if (name.startsWith("set")) {
        prefix = "set";
      } else if (name.startsWith("isSet")) {
        prefix = "isSet";
      } else if (name.startsWith("is")) {
        prefix = "is";
      } else if (name.startsWith("on")) {
        prefix = "on";
      } else if (name.startsWith("isValid")) {
        prefix = "isValid";
      } else if (name.startsWith("has")) {
        prefix = "has";
      } else if (name.startsWith("as")) {
        prefix = "as";
      } else if (name.startsWith("load")) {
        prefix = "load";
      } else if (name.startsWith("save")) {
        prefix = "save";
      } else if (name.startsWith("dump")) {
        prefix = "dump";
      } else if (name.startsWith("make")) {
        prefix = "make";
      } else if (name.startsWith("eval")) {
        prefix = "eval";
      } else if (name.startsWith("exists")) {
        prefix = "exists";
      } else if (name.startsWith("equals")) {
        prefix = "equals";
      } else if (name.startsWith("list")) {
        prefix = "list";
      }
      name = name.substring(prefix.length());
      publicMethods.put(String.format("%s%s-%d%s", name, SX.isSet(prefix) ? "-" + prefix : "",
              parameterCount, throwsException), method.toString());
    }
  }
  if (!silent) {
    List<String> publicMethodsKeys = publicMethods.keySet().stream().sorted().collect(Collectors.toList());
    for (String entry : publicMethodsKeys) {
      if (entry.startsWith("SX") || entry.startsWith("Option")) continue;
      log.p("%s", entry);
    }
  }
  return publicMethods;
}
 
Example 20
private static boolean isBuilder(Method method) {
    return method.getParameterCount() == 1 && method.getDeclaringClass().isAssignableFrom(method.getReturnType());
}