How to filter the return values of a method with AspectJ?
I would like to filter return values of methods which have a @Filter
annotation and return a Collection
, an Array
or a Map
by a certain predicate.
I tried something like:
@Pointcut("execution(@example.annotations.Filter * *(..)) "
+ "&& @annotation(filter) ")
public void filterOperation(final Filter filt开发者_JAVA百科er) {
/* ... */
}
But I get syntax errors if I add execution((java.util.Collection+ || java.util.Map+) * * (..))
to the PointCut above.
How would a solution look like, preferable one where I could error out if some method was annotated with @Filter
but would not return a collection?
Did you tried to use execution((java.util.Collection+ || java.util.Map+) *.* (..))
?
Or you can use:
@Pointcut("execution(@example.annotations.Filter java.util.Collection+ || java.util.Map+ *(..)) "
+ "&& @annotation(filter) ")
public void filterOperation(final Filter filter) {
/* ... */
}
You can handle return value the following way:
@AfterReturning(value="filterOperation(filter)", returning="collection")
public void handlingReturnValue(final Filter filter, Object collection) {
System.out.println(collection);
}
But I suppose it will be better to use separate advices for Map
s and Collection
s:
@Pointcut("execution(@Filter java.util.Collection+ *(..)) "
+ "&& @annotation(filter) ")
public void filterCollection(final Filter filter) {
/* ... */
}
@Pointcut("execution(@Filter java.util.Map+ *(..)) "
+ "&& @annotation(filter) ")
public void filterMap(final Filter filter) {
/* ... */
}
@AfterReturning(value="filterCollection(filter)", returning="collection")
public void handlingReturnCollection(final Filter filter, Collection collection) {
System.out.println(collection);
}
@AfterReturning(value="filterMap(filter)", returning="map")
public void handlingReturnMap(final Filter filter, Map map) {
System.out.println(map);
}
精彩评论