2012-09-04 95 views
1

我想使用斷言,但我不能,因爲方法的重載擔當起來......方法重載在Java中:該方法不適用於參數

我想用過濾一個數組(可變參數),我想在謂詞中使用內置方法,將數組轉換爲列表。

這是錯誤:在類型謂詞的方法,過濾器(可迭代,謂詞)是不適用的參數(類[],謂詞)

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

你的過濾器適用於方法 - 但你必須的集合。你不能將你的isTestMethod謂詞應用到一個類中...

你預計它會做什麼?你是否正在尋找一個過濾器來匹配有任何測試方法的類?

2

沒關係。我是一個白癡。

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

     } 
    } 
+0

'classes.getClass()'將返回代表數組類的類。 –

+0

對不起,我在吸毒(咳嗽藥),哈哈。 –