I'm confused, when executing following code:
@Test
public void testAccessible() throws NoSuchMethodException {
Constructor<LinkedList> constructor = LinkedList.class.getConstructor();
Assert.assertTrue(constructor.isAccessible());
}
the assertion fails, but LinkedList class has public
default constructor. So why isAccessible() returns false?
You could use
getModifiers()
method to determine accessibility/modifiers,isAccessible()
exists for different purpose.Go through documentation for
Modifiers
class in java. [ Link] It has methods necessary to determine visibility of a class member.isAccessible
allows reflection API to access any member at runtime. By callingField.setAcessible(true)
you turn off the access checks for this particular Field instance, for reflection only. Now you can access it even if it is private, protected or package scope, even if the caller is not part of those scopes. You still can't access the field using normal code. The compiler won't allow it.