Skip to content

Instantly share code, notes, and snippets.

@Gems
Last active April 27, 2022 10:55
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