Repository navigation
After Hook
This page is about
@Afterhooks specifically. You should make sure to read the general page about Hooks before it.
The @After hook lets you run code at the end of a method, after the original code.
There are two general purposes for @After patches:
- Calling your own code right at the end of a method
- Replacing or modifying a return value
After hooks require the AfterContext type for their patch handler's context parameter.
The ability to replace a return value makes the after hook one of the most versatile patches in PatchLib. Much of the game logic is handled by utility methods that are called from many other places. Changing what "answer" is returned provides easy ways to change the game's logic.
As an example patch, we are targeting all classes that inherit from BaseHullMod. We are specifically going to make the Onslaught Mk1 unable to have any hullmods installed. We can do this by replacing the return value of two of the hullmod plugin methods.
To get this done, we have the context.getReturnValue() and context.setReturnValue() methods. In the first handler, we simply check if the ship that the hullmod is on is the Onslaught Mk1 and return false if that is the case.
For the second patch, we also inspect the original return value. We do this to check that the original method hasn't already given another reason as to why something is incompatible,
and only replace the return value with our reason when no other branch of the original method has done so yet.
@Patch(target = @ClassMatch(subtype = BaseHullMod.class))
public class AfterExample {
@After(target = @MethodMatch(methodName = "isApplicableToShip"))
public static void afterIsApplicableToShip(AfterContext context) {
ShipAPI ship = (ShipAPI) context.getArg(0);
if (ship.getHullSpec().getBaseHullId().equals("onslaught_mk1")) {
context.setReturnValue(false);
}
}
@After(target = @MethodMatch(methodName = "getUnapplicableReason"))
public static void afterGetUnapplicableReason(AfterContext context) {
ShipAPI ship = (ShipAPI) context.getArg(0);
String returnValue = (String) context.getReturnValue();
if (returnValue == null && ship.getHullSpec().getBaseHullId().equals("onslaught_mk1")) {
context.setReturnValue("The Onslaught Mk1 can not be fitted with modern hullmods.");
}
}
}
It is worth noting that, in some cases, you can modify a return value without using setReturnValue. If a method returns a Vector2, for example, you could access its x variable and modify that, which would apply without you having to replace the full object.
- Home
- Introduction to Patchlib
- Patch Types
- Working with obfuscated code
- Example Patches
- Other utilities
- Patching with Kotlin
- Developer Documentation