Skip to content

Commit 3b626bf

Browse files
committed
PluginService: add a method to sort plugins
If you have a list of instances, but not their PluginInfo metadata anymore, the priority will not be known unless the plugin type extends HasPluginInfo. But regardless, we can look up the infos again, match the instances against the looked-up infos, and sort that way.
1 parent 72e613a commit 3b626bf

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
</parent>
1111

1212
<artifactId>scijava-common</artifactId>
13-
<version>2.68.1-SNAPSHOT</version>
13+
<version>2.69.0-SNAPSHOT</version>
1414

1515
<name>SciJava Common</name>
1616
<description>SciJava Common is a shared library for SciJava software. It provides a plugin framework, with an extensible mechanism for service discovery, backed by its own annotation processor, so that plugins can be loaded dynamically. It is used by downstream projects in the SciJava ecosystem, such as ImageJ and SCIFIO.</description>

src/main/java/org/scijava/plugin/PluginService.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,14 @@
3434

3535

3636
import java.util.Collection;
37+
import java.util.Collections;
38+
import java.util.Comparator;
3739
import java.util.List;
40+
import java.util.Map;
41+
import java.util.function.Function;
42+
import java.util.stream.Collectors;
3843

44+
import org.scijava.Priority;
3945
import org.scijava.service.SciJavaService;
4046

4147
/**
@@ -254,4 +260,23 @@ public interface PluginService extends SciJavaService {
254260
*/
255261
<PT extends SciJavaPlugin> PT createInstance(PluginInfo<PT> info);
256262

263+
/**
264+
* Sorts the given list of plugin instances by priority.
265+
*
266+
* @param instances List of plugin instances to sort.
267+
* @param type The type of plugin these instances represent.
268+
*/
269+
default <PT extends SciJavaPlugin> void sort(final List<PT> instances,
270+
final Class<PT> type)
271+
{
272+
// Create a mapping from plugin classes to priorities.
273+
final List<PluginInfo<PT>> plugins = getPluginsOfType(type);
274+
final Map<Class<?>, PluginInfo<PT>> infos = plugins.stream().collect(//
275+
Collectors.toMap(PluginInfo::getPluginClass, Function.identity()));
276+
277+
// Compare plugin instances by priority via the mapping.
278+
final Comparator<PT> comparator = (o1, o2) -> Priority.compare(//
279+
infos.get(o1.getClass()), infos.get(o2.getClass()));
280+
Collections.sort(instances, comparator);
281+
}
257282
}

0 commit comments

Comments
 (0)