The
java.lang.Class.cast()
method casts an object to the class or interface represented by this Class object.
This method returns the object after casting, or null if obj is null.
Exception ClassCastException
is thrown if the object is not null and is not assignable to the specified type.
The example program produced the following when run from the command window:
C:\work>java ClassDemo class ClassDemo Class B show() function Whoops Cannot cast A to B obj is class A b1 is class B a1 is class B
ClassDemo.java
import java.lang.*; class A { public static void show() { System.out.println("Class A show() function"); } } class B extends A { public static void show() { System.out.println("Class B show() function"); } } public class ClassDemo { public static void main(String[] args) { ClassDemo cls = new ClassDemo(); Class c = cls.getClass(); System.out.println(c); Object obj = new A(); B b1 = new B(); b1.show(); // casts object Object a1 = A.class.cast(b1); try { B b2 = B.class.cast(obj); } catch(ClassCastException e) { System.out.println("Whoops " + e.getMessage()); } System.out.println("obj is " + obj.getClass()); System.out.println("b1 is " + b1.getClass()); System.out.println("a1 is " + a1.getClass()); } }
Maintained by John Loomis, updated Thu Mar 22 15:02:21 2018