Close

Java Reflection - Field.setAccessible() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Field

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Fieldjava.lang.reflect.Fieldjava.lang.reflect.MemberMemberLogicBig

Method:

public void setAccessible(boolean flag)

Set the accessible flag for this field to the provided boolean value. This method is defined in the super class AccessibleObject. The semantics of this method has been changed significantly in Java 9.

From AccessibleObject#setAccessible():

Set the accessible flag for this reflected object to the indicated boolean value. A value of true indicates that the reflected object should suppress checks for Java language access control when it is used. A value of false indicates that the reflected object should enforce checks for Java language access control when it is used, with the variation noted in the class description.



This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C .
  • The member is protected static , D is public in a package that the module containing D exports to at least the module containing C , and C is a subclass of D .
  • D is in a package that the module containing D opens to at least the module containing C . All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

This method cannot be used to enable access to private members, members with default (package) access, protected instance members, or protected constructors when the declaring class is in a different module to the caller and the package containing the declaring class is not open to the caller's module.

See also: Java 9 Modules - Reflective Access via open and opens clauses.



public static void setAccessible(AccessibleObject[] array,
                                 boolean flag)

Above static method is defined in AccessibleObject class.

Convenience method to set the accessible flag for an array of reflected objects.

Examples


package com.logicbig.example.field;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;

public class SetAccessibleExample {

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
HashSet<String> set = new HashSet<>();
set.add("element1");
set.add("element2");

Field f = set.getClass().getDeclaredField("map");
boolean b = f.canAccess(set);
System.out.println("accessible: " + b);
System.out.println("modifiers: "+ Modifier.toString(f.getModifiers()));
if (!b) {
//without this Field.get or Field.set methods will throw exception
f.setAccessible(true);
}
//reading - using get method
HashMap<String, Object> theMap = (HashMap<String, Object>) f.get(set);
System.out.println(theMap);

//writing - using set method
HashMap<String, Object> newMap = new HashMap<>();
newMap.put("element3", new Object());
System.out.println("-- after setting new value --");
f.set(set, newMap);

//read again
HashMap<String, Object> theMap2 = (HashMap<String, Object>) f.get(set);
System.out.println(theMap2);
}
}

Output

accessible: false
modifiers: private transient
{element1=java.lang.Object@545d0097, element2=java.lang.Object@545d0097}
-- after setting new value --
{element3=java.lang.Object@58a9d365}
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.logicbig.example.field.SetAccessibleExample (file:/D:/examples/reflection-api/target/classes/) to field java.util.HashSet.map
WARNING: Please consider reporting this to the maintainers of com.logicbig.example.field.SetAccessibleExample
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

Check out this tutorial to learn about the warnings shown in above output.





All fields declared in the same class can be accessed without using setAccessible() even if they are private.

package com.logicbig.example.field;

import java.lang.reflect.Field;

public class SetAccessibleExample2 {
private String myStr = "str value";

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field f = SetAccessibleExample2.class.getDeclaredField("myStr");
Object v = f.get(new SetAccessibleExample2());
System.out.println(v);
}
}

Output

str value




All public fields can be accessed in other classes without using setAccessible.

package com.logicbig.example.field;

import java.lang.reflect.Field;
import java.math.BigDecimal;

public class SetAccessibleExample3 {

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field f = BigDecimal.class.getDeclaredField("TEN");
Object o = f.get(null);
System.out.println(o);
}
}

Output

10




All protected fields in the super class can be accessed without setAccessible method.

Following example extends JComponent class:

package com.logicbig.example.field;

import javax.swing.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class SetAccessibleExample4 extends JComponent {

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field f = JComponent.class.getDeclaredField("ui");
System.out.println("name: " + f.getName());
System.out.println("type: " + f.getType());
System.out.println("modifiers: " + Modifier.toString(f.getModifiers()));
Object o = f.get(new SetAccessibleExample4());
System.out.println("value: " + o);
}
}

Output

name: ui
type: class javax.swing.plaf.ComponentUI
modifiers: protected transient
value: null

package com.logicbig.example.field;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;

public class SetAccessibleExample5 {
private static class Test {
private String str;
private int number;
}

public static void main(String... args) throws NoSuchFieldException {
Field f1 = Test.class.getDeclaredField("str");
Field f2 = Test.class.getDeclaredField("number");

Test test = new Test();
System.out.println(f1.canAccess(test));
System.out.println(f2.canAccess(test));

AccessibleObject.setAccessible(new AccessibleObject[]{f1, f2}, true);

System.out.println(f1.canAccess(test));
System.out.println(f2.canAccess(test));
}
}

Output

false
false
true
true




See Also