Java : IllegalAccessException with Examples
IllegalAccessException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most IllegalAccessException methods.
Summary
An IllegalAccessException is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.
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 ()
Constructs an IllegalAccessException without a detail message.
final var e = new IllegalAccessException();
System.out.println(e); // java.lang.IllegalAccessException
IllegalAccessException (String s)
Constructs an IllegalAccessException with a detail message.
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.