Java : ReflectiveOperationException with Examples

ReflectiveOperationException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most ReflectiveOperationException methods.


Summary

Common superclass of exceptions thrown by reflective operations in core reflection.

Class diagram

public class Foo {
    public void aaa() {
    }
}
try {
    final var cls = Foo.class;

    final var aaa = cls.getMethod("aaa");
    System.out.println("aaa : OK!");

    final var bbb = cls.getMethod("bbb");

} catch (ReflectiveOperationException e) {
    System.out.println(e);
}

// Result
// ↓
//aaa : OK!
//java.lang.NoSuchMethodException: Foo.bbb()

Constructors

ReflectiveOperationException ()

Constructs a new exception with null as its detail message.

final var e = new ReflectiveOperationException();
System.out.println(e); // java.lang.ReflectiveOperationException

ReflectiveOperationException (String message)

Constructs a new exception with the specified detail message.

final var e = new ReflectiveOperationException("abcd");
System.out.println(e); // java.lang.ReflectiveOperationException: abcd
System.out.println(e.getMessage()); // abcd

ReflectiveOperationException (String message, Throwable cause)

Constructs a new exception with the specified detail message and cause.

final var cause = new NoSuchMethodException("XYZ");
final var e = new ReflectiveOperationException("abcd", cause);

System.out.println(e); // java.lang.ReflectiveOperationException: abcd
System.out.println(e.getMessage()); // abcd

System.out.println(e.getCause()); // java.lang.NoSuchMethodException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

ReflectiveOperationException (Throwable cause)

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

final var cause = new NoSuchMethodException("XYZ");
final var e = new ReflectiveOperationException(cause);

System.out.println(e); // java.lang.ReflectiveOperationException: java.lang.NoSuchMethodException: XYZ

System.out.println(e.getCause()); // java.lang.NoSuchMethodException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page