Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

NoSuchFieldException — failed field lookup

NoSuchFieldException is a checked exception raised when a lookup cannot find a field with the specified name. With reflection, the search scope matters: getField searches public fields, while getDeclaredField searches fields declared directly by the given type.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public class NoSuchFieldException extends ReflectiveOperationException

new NoSuchFieldException()
new NoSuchFieldException("Field not found")

Class<?> type = Example.class;
type.getField("fieldName");
type.getDeclaredField("fieldName");

NoSuchFieldException belongs to java.lang and extends ReflectiveOperationException. It is a checked exception: code must catch it or declare it with throws if it can leave the method. Its constructors are NoSuchFieldException() and NoSuchFieldException(String s); the latter accepts a detail message.

Class.getField(String) searches only public fields, including inherited fields. Class.getDeclaredField(String) searches fields declared directly by the given type, regardless of access modifier, but excludes inherited fields. Both methods throw NoSuchFieldException when no field is found within their search scope. This therefore does not necessarily mean that the field does not exist at all.

In the example, balance is private, so getField("balance") throws the exception, whereas getDeclaredField("balance") finds the field. Finding a Field object does not itself grant permission to read or modify the field's value; the example reads only its name.

When diagnosing a failure, check the field name, the inspected type, and whether you need public fields or directly declared fields. Catch this exception where a missing field can be handled meaningfully; otherwise propagate it.

Examples

public class Main {
    static class Account {
        private int balance;
    }

    public static void main(String[] args) throws NoSuchFieldException {
        try {
            Account.class.getField("balance");
            System.out.println("Public field found");
        } catch (NoSuchFieldException e) {
            System.out.println("Public field not found");
        }

        System.out.println(
            Account.class.getDeclaredField("balance").getName()
        );
    }
}

Result

Public field not found
balance

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources