Java reflection isAccessible method

I study reflection. When I execute the following code:

package main; import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws NoSuchFieldException, SecurityException { Base firstBase = new Base(); Field firstBaseField = firstBase.getClass().getDeclaredField("protectedBuffer"); System.out.println(firstBaseField.isAccessible()); } } 

This is the base class:

 package main; public class Base { private StringBuffer buffer; protected StringBuffer protectedBuffer; public StringBuffer buffer2; } 

the result will be false. But this is not true, because I can access protectedBuffer as follows: firstBase.protectedBuffer ?

+6
source share
3 answers

This is because you are not checking if the protectedBuffer field is available when you do firstBaseField.isAccessible();

What happens here is that you are checking the AccessibleObject value, which is the base class for the field. This flag does not tell you if the field is accessible using java access modifiers, it tells you whether these modifiers are ignored.

When you get false on firstBaseField.isAccessible() , it just means that the Java access rules are still in place and are not overridden by reflection mechanisms.

setAccessible ()

Set the available flag for this object to the specified boolean value. A value of true indicates that the reflected object should suppress access checks for the Java language when it is used. A value of false indicates that the reflected object should provide access control for the Java language.

Edit

To check if a field is accessible using java access modifiers, you can try to access it and catch an IllegalAccessException , as in the example below.

 Field field = instance.getClass().getDeclaredField("someField"); // IllegalAccessException field.get(instance); 
+6
source

You misunderstand this available flag. According to the documentation , when true is available, all access checks bypass (you can use this field or method, and Java will not check whether it is public or not). When false is available, access check works. And as it is written in the documentation, it is false by default for any AccessibleObject (even for fields or public methods).

+2
source

By default, all Fields obtained using Class#getDeclaredField(String name) have an accessible flag set to false . You will also get false for the public buffer2 field.

The Field class is a subclass of AccessibleObject :

By default, the reflected object is not available.

+1
source

All Articles