@Test public void testMatchSingleParameterMethod() throws Exception { Predicate<Method> predicate = MethodCoercions.matchSingleParameterMethod("singleParameterMethod", "42"); assertTrue(predicate.apply(singleParameterMethod)); assertFalse(predicate.apply(multiParameterMethod)); assertFalse(predicate.apply(singleCollectionParameterMethod)); }
@Test public void testMatchSingleCollectionParameterMethod() throws Exception { Predicate<Method> predicate = MethodCoercions.matchSingleParameterMethod("singleCollectionParameterMethod", ImmutableList.of("42")); assertFalse(predicate.apply(singleParameterMethod)); assertFalse(predicate.apply(multiParameterMethod)); assertTrue(predicate.apply(singleCollectionParameterMethod)); }
/** * Tries to find a single-parameter method with a parameter compatible with (can be coerced to) the argument, and * invokes it. * * @param instance the object to invoke the method on * @param methodName the name of the method to invoke * @param argument the argument to the method's parameter. * @return the result of the method call, or {@link org.apache.brooklyn.util.guava.Maybe#absent()} if method could not be matched. */ public static Maybe<?> tryFindAndInvokeSingleParameterMethod(final Object instance, final String methodName, final Object argument) { Class<?> clazz = instance.getClass(); Iterable<Method> methods = Arrays.asList(clazz.getMethods()); Optional<Method> matchingMethod = Iterables.tryFind(methods, matchSingleParameterMethod(methodName, argument)); if (matchingMethod.isPresent()) { Method method = matchingMethod.get(); Method accessibleMethod = Reflections.findAccessibleMethod(method).get(); try { Type paramType = method.getGenericParameterTypes()[0]; Object coercedArgument = TypeCoercions.coerce(argument, TypeToken.of(paramType)); return Maybe.of(accessibleMethod.invoke(instance, coercedArgument)); } catch (IllegalAccessException | InvocationTargetException e) { throw Exceptions.propagate(e); } } else { return Maybe.absent(); } }