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?
A constructor isn’t always public. Though we want it to be public because of each time we create an object of a class, we know the constructor would be called but if the constructor is defined in the private section we wouldn’t be able to call it. Hence we won’t be able to create our object of the class.
The ConstructorSift example illustrates how to search a class's declared constructors for one which has a parameter of a given type. The ConstructorAccess example searches for constructors in a given class with the specified access modifier. It also displays whether the constructor is synthetic (compiler-generated) or of variable arity.
A private constructor will not allow you to create objects outside the class scope( Well there is a way around that as well, see Singleton design pattern). But yeah, that's basically it. Public constructors allow you to create objects "Publicly" while private imposes a restriction.
The ConstructorAccess example searches for constructors in a given class with the specified access modifier. It also displays whether the constructor is synthetic (compiler-generated) or of variable arity.
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 calling Field.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.
From the Java Docs...
A value of false indicates that the reflected object should enforce Java language access checks
isAccessible
has more to do with Java's security manager then it does with it's public visibility
Class#getConstructor(Class...)
and Class#getConstructors
both return only the public
constructors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With