Why a public constructor is not accessible via reflection

2.8k views Asked by At

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?

3

There are 3 answers

0
D3V On BEST ANSWER

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.

0
MadProgrammer On

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

1
Anurag On
Declaration
public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

Pass your class object as parameter array like below.

Example :
package com.tutorialspoint;

import java.lang.reflect.*;

public class ClassDemo {

public static void main(String[] args) {

 try {
    // returns the Constructor object of the public constructor
    Class cls[] = new Class[] { String.class };
    Constructor c = String.class.getConstructor(cls);
    System.out.println(c);
 }
 catch(Exception e) {
    System.out.println(e);
 } 

} }

http://www.tutorialspoint.com/java/lang/class_getconstructor.htm