Why public constructor is not available through reflection

I got confused by executing the following code:

@Test public void testAccessible() throws NoSuchMethodException { Constructor<LinkedList> constructor = LinkedList.class.getConstructor(); Assert.assertTrue(constructor.isAccessible()); } 

the statement fails, but the LinkedList class has a public constructor by default. So why isAccessible () returns false?

+4
source share
3 answers

You can use the getModifiers() method to determine accessibility / modifiers, isAccessible() exists for different purposes.

Go through the documentation for the Modifiers class in java. [ Link] It has the methods needed to determine the visibility of a class member.

isAccessible allows isAccessible to reflect the API for accessing any member at runtime. By calling Field.setAcessible(true) , you disable access checks for this particular instance of the field, only for reflection. Now you can access it, even if it is a closed, protected, or package area, even if the caller is not part of these areas. You still cannot access the field using regular code. The compiler will not allow this.

+5
source

From Java Docs ...

A value of false indicates that the reflected object should provide access to the Java language

isAccessible has more to do with the Java Security Manager and then with its public visibility

Class#getConstructor(Class...) and Class#getConstructors both return only public constructors

+6
source
 Declaration public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException 

Pass your class object as an array of parameters, as shown 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

-2
source

Source: https://habr.com/ru/post/1496495/


All Articles