Java : NoSuchFieldException with Examples

NoSuchFieldException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most NoSuchFieldException methods.


Summary

Signals that the class doesn't have a field of a specified name.

Class diagram

public class Foo {
    public int aaa = 100;
}
try {
    final var cls = Foo.class;

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

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

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

// Result
// ↓
//aaa : OK!
//java.lang.NoSuchFieldException: bbb

Constructors

NoSuchFieldException ()

Constructor.

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

NoSuchFieldException (String s)

Constructor with a detail message.

final var e = new NoSuchFieldException("abcd");
System.out.println(e); // java.lang.NoSuchFieldException: 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.


Related posts

To top of page