5

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?

1
  • 1
    You could use getModifiers() method to determine accessibility/modifiers, isAccessible() exists for different purpose.
    – D3V
    Aug 12, 2013 at 4:47

3 Answers 3

7

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.

6

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

0
-2
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

1
  • 1
    1- LinkedList has a default constructor 2- What's that got to do with the question ?? Aug 12, 2013 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.