Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

Why a public constructor is not accessible via reflection

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?

Upvotes: 5

Views: 2967

Answers (3)

D3V
D3V

Reputation: 1593

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.

Upvotes: 7

Anurag
Anurag

Reputation: 137

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

Upvotes: -2

MadProgrammer
MadProgrammer

Reputation: 347204

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

Upvotes: 6

Related Questions