Java : IllegalAccessException with Examples
IllegalAccessException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most IllegalAccessException methods.
Summary
public class Foo {
private int num = 100;
}
final var cls = Foo.class;
final var obj = new Foo();
final var field = cls.getDeclaredField("num");
System.out.println("field : " + field);
System.out.println("-----");
try {
System.out.println("canAccess = " + field.canAccess(obj));
System.out.println("get = " + field.getInt(obj));
} catch (IllegalAccessException e) {
System.out.println("IllegalAccessException!");
}
System.out.println("-----");
try {
field.setAccessible(true);
System.out.println("canAccess = " + field.canAccess(obj));
System.out.println("get = " + field.getInt(obj));
} catch (IllegalAccessException e) {
System.out.println("IllegalAccessException!");
}
// Result
// ↓
//field : private int Foo.num
//-----
//canAccess = false
//IllegalAccessException!
//-----
//canAccess = true
//get = 100
Constructors
IllegalAccessException ()
final var e = new IllegalAccessException();
System.out.println(e); // java.lang.IllegalAccessException
IllegalAccessException (String s)
final var e = new IllegalAccessException("abcd");
System.out.println(e); // java.lang.IllegalAccessException: abcd
System.out.println(e.getMessage()); // abcd
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.