I am creating a Plugin system, where the plugin will be fetched from DB, my Implementation is like below
A base Plugin Interface
@Service
public interface Plugin{
somemethod();
}
In plugin package load all the plugin where inner package name will be plugin name and a class with plugin name
package <>.plugin.Myplugin
import ....
@Service
class MyPlugin implements Plugin {
@Override
somemethod() {}
}
I am loading all the implemented class of Plugin interface in dependency injection
@Controller
public class MyCon {
private List<Plugin> plugins
public MyCon(List<Plugin> plugins) {
this.plugins = plugins;
}
ssomefuncitonality() {
String objectNeedOfClass = <CLASS_NAME>;
//Here
System.out.println(this.plugins);
}
}
Here can see all the object in the list, but how can I fetch the perticular object of the provided class Name.
Iterate the list and check the class name:
Optional<Plugin> plugin = this.plugins.stream()
.filter(p -> p.getClass().getSimpleName().equals(objectNeedOfClass))
.findFirst();
If plugins
can be large and you do this often, build a map in the constructor:
private Map<String, Plugin> plugins
public MyCon(List<Plugin> plugins) {
this.plugins = plugins.stream().collect(Collectors.toMap(
p -> p.getClass().getSimpleName(), Function.identity()));
}
ssomefuncitonality() {
String objectNeedOfClass = ...;
Plugin plugin = this.plugins.get(objectNeedOfClass);
...
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments