插件管理器

插件管理器是你的插件在启动时被服务器加载后得到的。服务器加载你的插件,并找到它的由 Plugin 注解的主类,并提供一个新的实例到管理器。然后管理器将该实例保存在自己的集合中。你可以查看它并使用它自身提供的方法,从而允许你轻松地与另一个已加载的插件进行交互(如果你愿意的话)。

PluginManager 类

PluginManager 里面的公共方法用于获取加载的插件的当前集合以及它们的实例的信息。插件存储在一个 PluginContainer (下一节会提到)中,以允许我们可以方便地获取有关特定插件的一些信息。例如,你可以使用插件管理器( PluginManager )与另一个插件通信,抓取它的实例,并通过调用插件提供的方法提供可扩展性或扩展的特性。

获取插件管理器

你有数种不同的获得服务器的 PluginManager 实例的方法。

一:依赖注入

小技巧

参阅 依赖注入 页面来学习使用依赖注入。

PluginManager 是加载时注入到主类中的少数几个 API 实例之一。若要获取对它的引用,你可以创建一个新的字段来保存 PluginManager 实例,并使用 @Inject 注解。

import com.google.inject.Inject;
import org.spongepowered.api.plugin.PluginManager;

@Inject
private PluginManager pluginManager;

2. The Game Instance

小技巧

请参阅 Game 的 JavaDocs 以了解关于 Game 类的详细信息,包括其所有方法的使用方法。

为方便起见,一个 Game 的实例也可以提供服务端的 PluginManager 实例。

private PluginManager pluginManager = game.pluginManager();

现在你已经有了一个插件管理器的实例了,让我们开始使用它。

3. Using the Sponge Class

Sponge 类和 Game 类的使用方式类似,唯一的区别是 Sponge 类包含了一些调用 Game 类的静态方法。而 Sponge 类随时都可以访问到,所以说你其实也可以不用存储 Game 类的实例而去调用其方法。

import org.spongepowered.api.Sponge;

private PluginManager pluginManager = Sponge.pluginManager();

使用插件管理器

插件管理器提供了若干个方法用于处理插件。

有很多方法获取一个插件的信息,在下一节中我们就会讲到使用方式。显而易见,插件容器(Plugin Container)就是一个用于存储插件主类实例的“Container”。

使用插件管理器,我们可以获取已加载的所有插件:

import org.spongepowered.plugin.PluginContainer;

import java.util.Collection;

private Collection<PluginContainer> plugins = pluginManager.plugins();

当然,我们也可以直接获取到一个插件的插件容器的实例,如下所示:

private PluginContainer myOtherPlugin = pluginManager.plugin("myOtherPluginId").orElse(null);

PluginContainer 类

当我们从一个 PluginManager 中获取到插件容器的实例时,你会很快地注意到这并不是一个真正的插件主类的实例。也就是说你获取到的插件容器仅仅是 PluginContainer 的实例,其中包含了插件主类的 @Plugin 注解提供的信息,当然也有插件主类的实例。

The PluginContainer will hold any generic information about the plugin set by its owning developer. You can use information from here instead of hard-coding what you know about it in your supporting plugin. An example scenario would be if the owning developer changes the name of the plugin, references to the latter in the supporting plugin would not become wrong as a result of this change, provided you've used the method PluginContainer#metadata() to get its metadata which contains the name of the plugin.

private PluginContainer myOtherPlugin = pluginManager.getPlugin("myOtherPluginId").orElse(null);
private MyOtherPlugin pluginInstance = (MyOtherPlugin) myOtherPlugin.instance().orElse(null);

备注

PluginContainer#instance() will return as an Object. You need to cast it as the target plugin after obtaining it from the container.