Skip to content

Commit 04b08df

Browse files
committed
PTService: add utility method to create a plugin
Surprisingly, the PluginService API does not have a method to create a plugin from its class. You can only create one from its associated PluginInfo. So instantiating a plugin becomes a two-step process: 1. Ask the PluginService for the PluginInfo of a given plugin Class. 2. Tell the PluginService to create an instance from that PluginInfo. And this process is not fully type-safe, since the PluginInfo#createInstance(PluginInfo) method only knows the object is of type PT, not P. To help address this limitation, each PTService now has a handy create(Class<P extends PT>) method for creating an instance of that plugin class. This is useful, since using "new" directly is not enough; the plugin will not have the application context injected as needed.
1 parent 755742f commit 04b08df

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,13 @@ public List<PluginInfo<PT>> getPlugins() {
6060
return pluginService.getPluginsOfType(getPluginType());
6161
}
6262

63+
@Override
64+
public <P extends PT> P create(final Class<P> pluginClass) {
65+
final PluginInfo<PT> info =
66+
pluginService.getPlugin(pluginClass, getPluginType());
67+
@SuppressWarnings("unchecked")
68+
final P plugin = (P) pluginService.createInstance(info);
69+
return plugin;
70+
}
71+
6372
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,7 @@ public interface PTService<PT extends SciJavaPlugin> extends Service {
9595
/** Gets the type of plugins managed by this service. */
9696
Class<PT> getPluginType();
9797

98+
/** Creates an instance of the given plugin class. */
99+
<P extends PT> P create(final Class<P> pluginClass);
100+
98101
}

0 commit comments

Comments
 (0)