1

我正在尝试使用谓词,但我不能,因为方法重载正在起作用......

我想将过滤器与数组(varargs)一起使用,并且我想在谓词中使用内置方法,该方法将数组过滤为转换为列表。

这是错误:Predicates 类型中的方法 filter(Iterable, Predicate) 不适用于参数 (Class[], Predicate)

private static final Predicate<Method> isTestMethod = new Predicate<Method>() {
    @Override
    public boolean evaluate(Method input) {
        return input.isAnnotationPresent(Test.class);
    }
};

public static void testClasses(Class<?>... classes) {
    for (Method method : filter(classes, isTestMethod)) {

    }
}

这是谓词方法:

/**
 * Returns the elements of <tt>unfiltered</tt> that satisfy a predicate.
 * 
 * @param unfiltered An iterable containing objects of any type
 * that will be filtered and used as the result.
 * @param predicate The predicate to use for evaluation.
 * @return An iterable containing all objects which passed the predicate's evaluation.
 */
public static <T> Iterable<T> filter(Iterable<T> unfiltered, Predicate<T> predicate) {
    checkNotNull(unfiltered);
    checkNotNull(predicate);

    List<T> result = new ArrayList<T>();
    Iterator<T> iterator = unfiltered.iterator();
    while (iterator.hasNext()) {
        T next = iterator.next();
        if (predicate.evaluate(next)) {
            result.add(next);
        }
    }
    return result;
}

/**
 * Returns the elements of <tt>unfiltered</tt> that satisfy a predicate.
 * 
 * @param unfiltered An array containing objects of any type
 * that will be filtered and used as the result.
 * @param predicate The predicate to use for evaluation.
 * @return An iterable containing all objects which passed the predicate's evaluation.
 */
public static <T> Iterable<T> filter(T[] unfiltered, Predicate<T> predicate) {
    return filter(Arrays.asList(unfiltered), predicate);
}
4

2 回答 2

4

您的过滤器适用于方法- 但您有一个的集合。您不能将isTestMethod谓词应用于类...

What did you anticipate it would do? Were you perhaps looking for a filter to match classes which had any test methods?

于 2012-09-04T14:54:28.443 回答
2

Nevermind. I am an idiot.

    for (Class<?> testClass : classes) {
        for (Method method : filter(testClass.getClass().getMethods(), isTestMethod)) {

        }
    }
于 2012-09-04T14:54:51.813 回答