简体   繁体   English

所有具有特定注释并实现特定接口的类

[英]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. 我正在使用org.reflections在多模块应用程序中查找某些类。

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. 然后通过在两个集合之一上调用Set.retainAll()方法并传递另一个作为参数来保持两者的交集。

boolean retainAll(Collection c); boolean keepAll(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. 结果, allClasses将仅包含两个Set中存在的Class实例。

You've already got two sets. 你已经有两套了。 Why not use them and do some set operations? 为什么不使用它们并进行一些设置操作?

ddd has all the classes that implement MyInterface . ddd具有实现MyInterface所有类。 classes has all the classes that are marked with MyAnnotation . classes具有标有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. 在Java Set ,没有并unionintersectionsubtract To do an intersection you should call retainAll , so: 要进行交集,应调用retainAll ,因此:

 ddd.retainAll(classes)

is what you need. 是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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