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

The following examples show how to use java.lang.reflect.Method#getParameterCount() . 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: IdToEntityConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 File: LinkCellClickListener.java    From cuba with 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 File: FallbackMethod.java    From resilience4j with 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 4
Source File: KerberosTixDateTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 5
Source File: ReplaceOverride.java    From java-technology-stack with 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 6
Source File: ReflectionTableParser.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
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 7
Source File: ModuleOverrideHandler.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 8
Source File: Reflection.java    From dynamic-object with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
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 9
Source File: ReflectUtils.java    From turbo-rpc with 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 10
Source File: ParameterMapper.java    From CheckPoint with 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 11
Source File: SecurityManager.java    From beihu-boot with 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 12
Source File: CanonCameraMockTest.java    From canon-sdk-java with 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 13
Source File: KafkaStreamsStreamListenerSetupMethodOrchestrator.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
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 14
Source File: OnMessageMethodInvoker.java    From spring-boot-netty with MIT License 5 votes vote down vote up
@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 15
Source File: ModuleOverrideHandler.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 16
Source File: DispatcherHandler.java    From mangooio with 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 17
Source File: QuarkusTestNgCallbacks.java    From quarkus with 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 18
Source File: SX.java    From SikuliNG with 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 19
Source File: AbstractThriftMetadataBuilder.java    From drift with Apache License 2.0 4 votes vote down vote up
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 20
Source File: Reflection.java    From dynamic-object with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
private static boolean isBuilder(Method method) {
    return method.getParameterCount() == 1 && method.getDeclaringClass().isAssignableFrom(method.getReturnType());
}