I'm trying to initialize a MethodHandle
for a non-public method in an upstream library.
private static Method OF_METHOD;
static Method ofMethod() {
if (OF_METHOD == null) {
try {
OF_METHOD = RequestObject.class.getDeclaredMethod(
"of", Class.class, String.class, String.class,
Object.class, Object.class);
if (!OF_METHOD.isAccessible()) {
OF_METHOD.setAccessible(true);
}
} catch (final NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
}
return OF_METHOD;
}
private static MethodHandle OF_HANDLE;
static MethodHandle ofHandle() {
if (OF_HANDLE == null) {
try {
OF_HANDLE = MethodHandles.lookup().unreflect(ofMethod());
} catch (final ReflectiveOperationException roe) {
throw new RuntimeException(roe);
}
}
return OF_HANDLE;
}
And my SpotBugs Bug Detecter Report says the ofMethod()
has a LI_LAZY_INIT_UPDATE_STATIC problem.
I understand what it's saying. I see those two steps(assigning and setting accessible) are problematic in multi-threaded environment.
How can I solve the problem? Should I apply Double-checked locking?
Or should I put ofMethod()
logic into ofHandle()
?