Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java class literals: `TypeName.class`

A `.class` literal gives you the object that represents a named type. Use it to filter values, specify an `EnumMap` key type, select a monitor, or configure a field updater.

Version: Java SE 21

Syntax

TypeName { [] } . class
NumericType { [] } . class
boolean { [] } . class
void . class

Braces denote zero or more repetitions; they are not Java tokens in the expression.
Examples: String.class, Runnable.class, String[].class, int[].class, int.class, void.class

In Java SE 21, TypeName.class evaluates to the Class object for the named type. It neither creates an instance of that type nor triggers its initialization by itself. For an accessible reference type C, C.class has type Class<C>; this includes interfaces and arrays. int.class and Integer.class both have type Class<Integer>, but represent the primitive and wrapper respectively. void.class has type Class<Void>. In the shorthand Class literal T.class, T stands for a type name, not a type variable. List<String>.class is illegal; List.class does not retain the element type.

A literal selects the type written in the code. By contrast, obj.getClass() returns the object's actual runtime class and throws NullPointerException on a null receiver. Type.class has type Class<Type> and represents the declared enum Type, not a constant. A constant with its own class body has a different runtime class, but getDeclaringClass() still returns Type.class. new EnumMap<>(Type.class) selects the constructor for an empty map keyed by Type; for an enum named Status, pass Status.class instead.

In <T> List<T> select(List<?> values, Class<T> type), the supplied token links the runtime check to the result's element type. String.class, Integer.class, StringBuilder.class, TextNote.class, and Metric.class select String, Integer, StringBuilder, TextNote, and Metric, respectively. isInstance accepts compatible non-null objects, including subclass instances or interface implementations. Applying cast after that check returns the same reference typed as T; without the check, an incompatible non-null value causes ClassCastException. Filtering does not turn a StringBuilder into a String.

synchronized (Main.class) acquires the monitor of the Class<Main> object, the same one used by a static synchronized method declared in Main. It is not the monitor of this or of a separately created lock. Classes with the same name defined by different class loaders can have different monitors. Use a private lock object if outside code should not be able to acquire the same monitor.

In AtomicIntegerFieldUpdater.newUpdater(Metric.class, "count"), the literal identifies the declaring class and the instance type for AtomicIntegerFieldUpdater<Metric>. The name "count" selects an accessible volatile int instance field. A missing, inaccessible, or incorrectly declared field causes updater creation to fail. Incrementing the field takes a particular Metric instance, not the class token.

Examples

import java.util.EnumMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class Main {
    enum Type { READY {} }
    record TextNote(String text) {}
    static final class Metric {
        volatile int count;
    }

    static <T> List<T> select(List<?> values, Class<T> type) {
        return values.stream().filter(type::isInstance).map(type::cast).toList();
    }

    void demo() {
        Metric metric = new Metric();
        List<?> values = List.of(new TextNote("ready"), metric, 7,
                                 new StringBuilder("not a String"));
        List<TextNote> notes = select(values, TextNote.class);
        List<Metric> metrics = select(values, Metric.class);
        List<Integer> integers = select(values, Integer.class);
        List<String> strings = select(values, String.class);
        System.out.println("note=" + notes.get(0).text());
        System.out.println("metric matches=" + metrics.size());
        System.out.println("integers=" + integers);
        System.out.println("strings=" + strings);

        EnumMap<Type, Integer> counts = new EnumMap<>(Type.class);
        AtomicIntegerFieldUpdater<Metric> updater =
                AtomicIntegerFieldUpdater.newUpdater(Metric.class, "count");
        counts.put(Type.READY, updater.incrementAndGet(metric));
        System.out.println("updated=" + counts.get(Type.READY));
        System.out.println("declaring enum=" + (Type.READY.getDeclaringClass() == Type.class));
        System.out.println("same runtime class=" + Type.class.equals(Type.READY.getClass()));

        Object lock = new Object();
        synchronized (Main.class) {
            System.out.println("class monitor=" + Thread.holdsLock(Main.class));
            System.out.println("instance monitor=" + Thread.holdsLock(this));
            System.out.println("separate monitor=" + Thread.holdsLock(lock));
        }
    }

    public static void main(String[] args) {
        new Main().demo();
    }
}

Result

note=ready
metric matches=1
integers=[7]
strings=[]
updated=1
declaring enum=true
same runtime class=false
class monitor=true
instance monitor=false
separate monitor=false

The empty `strings` list shows that a `StringBuilder` does not match `String.class`. Of the three monitors checked, the thread holds only the class monitor. This is not a concurrency test.

Related lessons

  • Java · Lesson 13 · Advanced · Version: 2
  • Java · Lesson 19 · Advanced · Version: 2
  • Java · Lesson 27 · Advanced · Version: 2
  • Java · Lesson 28 · Advanced · Version: 2
  • Java · Lesson 32 · Advanced · Version: 2
  • Java · Lesson 10 · Intermediate · Version: 2
  • Java · Lesson 36 · Intermediate · Version: 2
  • Java · Lesson 37 · Intermediate · Version: 2

Sources