Set the accessible flag for this method to the provided boolean value. This method is defined in the super class AccessibleObject. The semantics of this method has been changed significantly in Java 9.
Set the
accessible
flag for this reflected object to the indicated boolean value. A value of
true
indicates that the reflected object should suppress checks for Java language access control when it is used. A
value of
false
indicates that the reflected object should enforce checks for Java language access control when it is used, with
the variation noted in the class description.
This method may be used by a caller in class
C
to enable access to a
member
of
declaring class
D
if any of the following hold:
-
C
and
D
are in the same module.
- The member is
public
and
D
is
public
in a package that the module containing
D
exports
to at least the module containing
C
.
- The member is
protected
static
,
D
is
public
in a package that the module containing
D
exports to at least the module containing
C
, and
C
is a subclass of
D
.
-
D
is in a package that the module containing
D
opens
to at least the module containing
C
. All packages in unnamed and open modules are open to all modules and so this method always succeeds when
D
is in an unnamed or open module.
This method cannot be used to enable access to private members, members with default (package) access, protected
instance members, or protected constructors when the declaring class is in a different module to the caller and
the package containing the declaring class is not open to the caller's module.
Without setting this flag:
package com.logicbig.example.method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SetAccessibleExample2 {
private static class Test {
private static void doSomething() {
System.out.println("working");
}
}
public static void main(String... args) throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException {
Method m = SetAccessibleExample2.Test.class.getDeclaredMethod("doSomething");
//m.setAccessible(true);
m.invoke(null);
}
}
Output
Caused by: java.lang.IllegalAccessException: class com.logicbig.example.method.SetAccessibleExample2 cannot access a member of class com.logicbig.example.method.SetAccessibleExample2$Test with modifiers "private static"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:360)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:589)
at java.base/java.lang.reflect.Method.invoke(Method.java:556)
at com.logicbig.example.method.SetAccessibleExample2.main(SetAccessibleExample2.java:24)
... 6 more