Skip to content

Commit

Permalink
feature: Spoon Filter implements java.util.function.Predicate (#1798)
Browse files Browse the repository at this point in the history
  • Loading branch information
pvojtechovsky authored and monperrus committed Jan 1, 2018
1 parent fe9e5a0 commit 2e60d6b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/main/java/spoon/reflect/visitor/Filter.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
*/
package spoon.reflect.visitor;

import java.util.function.Predicate;

import spoon.reflect.declaration.CtElement;

/**
Expand All @@ -25,11 +27,15 @@
* the type of the filtered elements (an element belonging to the
* filtered element must be assignable from <code>T</code>).
*/
public interface Filter<T extends CtElement> {
public interface Filter<T extends CtElement> extends Predicate<T> {
/**
* Tells if the given element matches.
* @param element - the element to be checked for a match. Parameter element is never null if {@link Query} is used.
*/
boolean matches(T element);

@Override
default boolean test(T element) {
return matches(element);
}
}
12 changes: 11 additions & 1 deletion src/test/java/spoon/test/filters/FilterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;
Expand All @@ -14,12 +15,12 @@
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.function.Predicate;

import org.junit.Before;
import org.junit.Test;

import spoon.Launcher;
import spoon.SpoonException;
import spoon.reflect.code.CtCFlowBreak;
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtFieldAccess;
Expand Down Expand Up @@ -1284,4 +1285,13 @@ public void testNameFilterWithGenericType() {
assertEquals(1, ctFields.size());
assertTrue(ctFields.get(0) instanceof CtField);
}

@Test
public void testFilterAsPredicate() throws Exception {
CtClass<?> foo = factory.Package().get("spoon.test.filters").getType("Foo");
//contract: Spoon Filter is compatible with java.util.function.Predicate
Predicate predicate = new NamedElementFilter<>(CtClass.class, "Foo");
assertTrue(predicate.test(foo));
assertFalse(predicate.test(foo.getTypeMembers().get(0)));
}
}

0 comments on commit 2e60d6b

Please sign in to comment.