How to get a field with Reflection in Java
Today, while looking into server-less Wiremock, I wanted to retrieve a (private) field from a class.
Interestingly, most of the Stack Overflow posts I found weren't super helpful, but this reply from Lino on StackOverflow helped me track it down:
WireMockServer server = new WireMockServer();
try {
Field field = WireMockServer.class.getDeclaredField("stubRequestHandler");
field.setAccessible(true);
handler = (StubRequestHandler) field.get(server);
// yay!
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}