Close

Java Reflection - Field.trySetAccessible() 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 final boolean trySetAccessible()

Set the accessible flag for this reflected object to true if possible. This method sets the accessible flag, as if by invoking setAccessible(true) , and returns the possibly-updated value for the accessible flag. If access cannot be enabled, i.e. the checks or Java language access control cannot be suppressed, this method returns false (as opposed to setAccessible(true) throwing InaccessibleObjectException when it fails).


Examples


package com.logicbig.example.field;

import java.lang.reflect.Field;

public class TrySetAccessibleExample {
private static class Test {
private static int number;
}

public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
Field f = Test.class.getDeclaredField("number");
System.out.println(f.canAccess(null));
boolean b = f.trySetAccessible();
System.out.println(b);
}
}

Output

false
true




package com.logicbig.example.field;

import java.lang.reflect.Field;

public class TrySetAccessibleExample2 {
private static class Test {
private int number;
}

public static void main(String... args) throws NoSuchFieldException {
Field f = Test.class.getDeclaredField("number");
Test test = new Test();
System.out.println(f.canAccess(test));
boolean b = f.trySetAccessible();
System.out.println(b);
}
}

Output

false
true




See Also