Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java reflection: type names, declared members, and constructors

Read a type's name, look up fields and methods declared directly on it, and create an instance with a selected constructor without confusing discovery with access.

Version: Java SE 21

Syntax

String Class.getName()
String Class.getSimpleName()
Field[] Class.getDeclaredFields()
Field Class.getDeclaredField(String name) throws NoSuchFieldException
Method[] Class.getDeclaredMethods()
Method Class.getDeclaredMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException
Constructor<T> Class<T>.getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException
T Constructor<T>.newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

In Java SE 21, Class.getName() gives the binary name of a non-hidden class or interface, such as demo.Main$Item. Hidden types have a special name with a suffix after /; arrays use an encoding such as [I; primitives and void use their keyword spelling. Class.getSimpleName() gives the simple source name, such as Item, returns an empty string for an anonymous class, and adds [] to the component's simple name for an array.

getDeclaredFields() and getDeclaredMethods() return Field[] and Method[] respectively. They include members declared directly on the type at any visibility, even private, but exclude inherited members. Plain getFields() and getMethods() are limited to public members and can include inherited ones. The returned order is unspecified; the method list may contain bridge or other synthetic methods.

getDeclaredField(name) looks up a field by name and throws NoSuchFieldException if absent. getDeclaredMethod(name, parameterTypes...) matches the name and exact formal parameter types in declaration order. getDeclaredConstructor(parameterTypes...) matches parameters the same way and returns a Constructor<T>, even for a non-public constructor. A missing method or constructor throws NoSuchMethodException. Lookup does not box or match subtypes: int.class and Integer.class are different. For a String... parameter, look up String[].class; for a zero-parameter signature, omit the type arguments. Return type is not a method lookup input: if several methods match, the one whose return type is more specific than all the others wins if it exists; otherwise the choice is arbitrary.

Finding a member does not grant permission to use it. To suppress access checks for a private member in another module, the package must be open to the caller's module. If access restrictions prevent suppression, trySetAccessible() returns false, whereas setAccessible(true) throws InaccessibleObjectException. In Java SE 21, both methods can throw SecurityException if an installed security manager denies ReflectPermission("suppressAccessChecks").

Constructor lookup uses Class objects to specify parameter types. To call the selected constructor, Constructor.newInstance takes actual argument values; a Class object is a valid argument value if it is compatible with the corresponding parameter type. It permits conversions such as unboxing and valid widening. For a non-static member class, pass the enclosing class type first at lookup and its instance first at invocation. If checks pass, the class is initialized if necessary before the object is created. Denied access causes IllegalAccessException, a wrong argument count or incompatible types or an enum constructor cause IllegalArgumentException, and an abstract class causes InstantiationException. An exception thrown by the constructor is wrapped in InvocationTargetException; use getCause() to inspect it. Class initialization can fail separately with ExceptionInInitializerError. Do not confuse this API with Class.newInstance(), which only calls a no-argument constructor and has been deprecated since Java 9.

Examples

package demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Arrays;

public class Main {
    static class Base {
        public int inherited;
        public void reset() {}
    }

    static final class Item extends Base {
        private final int count;

        private Item(int count) {
            this.count = count;
        }

        private String label(int offset) { return "count=" + (count + offset); }
        public String label(String prefix) { return prefix + count; }
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        Class<Item> type = Item.class;
        System.out.println(type.getName());
        System.out.println(type.getSimpleName());
        System.out.println(Arrays.stream(type.getDeclaredFields())
                .map(Field::getName).sorted().toList());
        System.out.println(Arrays.stream(type.getDeclaredMethods())
                .map(m -> m.getName() + "(" + m.getParameterTypes()[0].getSimpleName() + ")")
                .sorted().toList());
        System.out.println(type.getDeclaredField("count").getType().getName());
        var method = type.getDeclaredMethod("label", int.class);
        Constructor<Item> constructor = type.getDeclaredConstructor(int.class);
        Item item = constructor.newInstance(7);
        System.out.println(method.invoke(item, 0));
    }
}

Result

demo.Main$Item
Item
[count]
[label(String), label(int)]
int
count=7

The lists are sorted before printing. `inherited` and `reset` come from `Base`, so they do not appear in the `Item` lists. `int.class` selects `label(int)`, and `7` is passed to the constructor. `Main` and `Item` are nestmates, so the private constructor and method need no access-check override.

Related lessons

  • Java · Lesson 54 · Advanced · Version: 2

Sources