Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Class.cast — checked casting with Class<T>

When you have the target type in a `Class<T>` variable, use `cast` to get a reference of type `T` to the same object. Use `isInstance` to check a non-null value before casting.

Version: Java SE 21

Syntax

public T cast(Object obj)

// Instance method of java.lang.Class<T>:
// For Class<T> type and Object value:
T result = type.cast(value);

Class.cast is an instance method of java.lang.Class<T>. The call type.cast(value) checks at run time whether the value is compatible with the type represented by type. It returns a reference to the same object, with compile-time type T. It does not copy or change the object. A subclass instance or an object implementing the target interface can also pass the check.

If type.isInstance(value) returns true, you can call type.cast(value) on that same value inside the if branch. isInstance only returns a boolean; it does not change the type of value. For null, isInstance returns false, but cast returns null. An incompatible non-null argument causes a ClassCastException.

When the target type is named directly in the code, you can write (CharSequence) value. Use type.cast(value) when the type is passed as a Class<T>. The method does not perform numeric conversions, and List.class.cast(value) does not check whether the list's elements are String objects.

Examples

public class Main {
    public static void main(String[] args) {
        Class<CharSequence> type = CharSequence.class;
        Object value = new StringBuilder("Java");

        if (type.isInstance(value)) {
            CharSequence text = type.cast(value);
            System.out.println("length: " + text.length());
            System.out.println("same object: " + (text == value));
        }

        System.out.println("isInstance(null): " + type.isInstance(null));
        System.out.println("cast(null): " + type.cast(null));

        try {
            type.cast(Integer.valueOf(7));
        } catch (ClassCastException e) {
            System.out.println("incompatible: ClassCastException");
        }
    }
}

Result

length: 4
same object: true
isInstance(null): false
cast(null): null
incompatible: ClassCastException

`StringBuilder` implements `CharSequence`, so after the check you can call `length()` through `text`. The `==` comparison confirms that both references point to the same object. The remaining lines show the different behavior for `null` and the exception for an incompatible `Integer`.

Related lessons

  • Java · Lesson 36 · Intermediate · Version: 2
  • Java · Lesson 37 · Intermediate · Version: 2

Sources