Last active
April 27, 2022 10:55
-
-
Save Gems/32ff31eece3b09bd49c6ec3d02acfb18 to your computer and use it in GitHub Desktop.
Non-accessible class methods accessor (Java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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