简体   繁体   中英

all classes which have a certain annotation and implement a certain interface

I am using org.reflections to find certain classes in a multi module application.

I am able to find all classes which are implementing a certain interface:

Reflections reflections = new Reflections("my.package");    
Set<Class<? extends MyInterface>> ddd = reflections.getSubTypesOf(MyInterface.class);

I am able to find all classes which are having a certain annotation.

Reflections reflections = new Reflections("my.package");
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(MyAnnotation.class);

However, i can't find a way to find all classes that are implementing that interface AND have the wanted annotation.

How can I combine these two approaches? Is it even possible?

You may retrieve both as you do actually.
Then keep the intersection of both by invoking the Set.retainAll() method on one of two sets and pass the other as parameter.

boolean retainAll(Collection c);

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

For example try it :

Reflections reflection = new Reflections("my.package");
Set<Class<? extends MyInterface>> matchingClasses = reflection.getSubTypesOf(MyInterface.class);    
Set<Class<?>> annotationClasses = reflection.getTypesAnnotatedWith(MyAnnotation.class);

matchingClasses.retainAll(annotationClasses);

As result, allClasses will contain only Class instances that are present in the two Sets.

You've already got two sets. Why not use them and do some set operations?

ddd has all the classes that implement MyInterface . classes has all the classes that are marked with MyAnnotation . And I want all the classes that satisfies both criteria. You should probably know what kind of set operation you need now - Intersection.

In Java Set s don't have union , intersection or subtract methods. To do an intersection you should call retainAll , so:

 ddd.retainAll(classes)

is what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM