public class CanAccessExample { private static class Test { private int number; }
public static void main(String... args) throws NoSuchFieldException { Field f = Test.class.getDeclaredField("number"); Test testInstance = new Test(); boolean b = f.canAccess(testInstance); System.out.println(b); if(!b){ f.setAccessible(true); System.out.println(f.canAccess(testInstance)); } } }
Output
true
package com.logicbig.example.field;
import java.lang.reflect.Field;
public class CanAccessExample2 { private int number; private static String str;
public static void main(String... args) throws NoSuchFieldException { Field f = CanAccessExample2.class.getDeclaredField("number"); System.out.println(f.canAccess(new CanAccessExample2())); //static field Field f2 = CanAccessExample2.class.getDeclaredField("str"); System.out.println(f2.canAccess(null)); } }