Close

Java Reflection - Field.canAccess() 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 canAccess(Object obj)

Test if the caller can access this field object.


Examples


package com.logicbig.example.field;

import java.lang.reflect.Field;

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

false
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));
}
}

Output

true
true




See Also