Line 123: |
Line 123: |
| instances: '''injecting''' into a field, or a '''callback method'''. | | instances: '''injecting''' into a field, or a '''callback method'''. |
| | | |
− | ==== Injecting into a Field ==== | + | ==== Getting the Capability ==== |
| | | |
− | A <code>Capability</code> can be injected automatically into a field as soon as it gets created by Forge, following the | + | A <code>Capability</code> can obtained at any time using <code>CapabilityManager#get</code>. This takes in an anonymous <code>CapabilityToken</code> to still allow for a soft dependency system while also keeping hold of any generic information needed. As such, you can always obtain a non-null capability. |
− | principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user
| |
− | that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method
| |
− | instead of the callback approach.
| |
− | | |
− | To inject the <code>Capability</code> into a field, all that's needed is to declare a <code>static</code> field of type
| |
− | <code>Capability<T></code>, where <code>T</code> represents the capability interface, and annotate it with
| |
− | <code>@CapabilityInject(T.class)</code>.
| |
− | | |
− | For a more practical example, consider the following snippet:
| |
| | | |
| <syntaxhighlight lang="java"> | | <syntaxhighlight lang="java"> |
− | @CapabilityInject(IItemHandler.class)
| + | public static Capability<IItemHandler> ITEM_HANDLER_CAPABILITY = CapabilityManager.get(new CapabilityToken<>(){}); |
− | public static Capability<IItemHandler> ITEM_HANDLER_CAPABILITY = null; | |
| </syntaxhighlight> | | </syntaxhighlight> |
| | | |
− | The above code will let Forge know that the field <code>ITEM_HANDLER_CAPABILITY</code> should be injected with the | + | The above code will let Forge know that the field <code>ITEM_HANDLER_CAPABILITY</code> should be analogous with the <code>IItemHandler</code> capability. Note that this does not mean the capability is accessible or registered. To check if it is, call <code>Capability#isRegistered</code>. |
− | unique instance of the <code>IItemHandler</code> capability. Assigning the field to <code>null</code> allows us to
| |
− | provide a reasonable fallback in case the capability we want hasn't been registered yet.
| |
| | | |
− | This injection is, for obvious reasons, redundant, since that capability is also available through | + | This is, for obvious reasons, redundant, since that capability is also available through |
| <code>CapabilityItemHandler</code>. | | <code>CapabilityItemHandler</code>. |
| | | |