Skip to content

Instantly share code, notes, and snippets.

@Gems
Last active April 27, 2022 10:55
Show Gist options
  • Save Gems/32ff31eece3b09bd49c6ec3d02acfb18 to your computer and use it in GitHub Desktop.
Save Gems/32ff31eece3b09bd49c6ec3d02acfb18 to your computer and use it in GitHub Desktop.
Non-accessible class methods accessor (Java)
class Accessor {
private static final MethodHandle methodHandle;
private static final String METHOD_NAME = "methodName";
static {
try {
val declaredMethod = Target.class.getDeclaredMethod(METHOD_NAME);
declaredMethod.setAccessible(true);
methodHandle = MethodHandles.lookup()
.unreflect(declaredMethod)
.asType(MethodType.methodType(ReturnType.class, Target.class));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@SneakyThrows
public static ReturnType method(Target target) {
//noinspection unchecked
return (ReturnType) methodHandle.invokeExact(target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment