Java Class. cast method, javaclass. cast Method
1. Java api
public T cast(Object obj);
Casts an object to the class or interface represented
The general explanation means to replace an object with a class or interface.
2. Sample Code
/** * Created by shengke on 2016/10/22. */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 TestCast { public static void main(String[] args) { TestCast cls = new TestCast(); Class c = cls.getClass(); System.out.println(c); Object obj = new A(); B b1 = new B(); b1.show(); // casts object A a = new A(); a = A.class.cast(b1); System.out.println(obj.getClass()); System.out.println(b1.getClass()); System.out.println(a.getClass()); }}
Execution result
class com.scot.effective.genericity.TestCastClass B show() functionclass com.scot.effective.genericity.Aclass com.scot.effective.genericity.Bclass com.scot.effective.genericity.B
Core: a = A. class. cast (b1); converting a to B is easy to produce misunderstanding of converting b1 to.
3. Source Code
/** * Casts an object to the class or interface represented * by this {@code Class} object. * * @param obj the object to be cast * @return the object after casting, or null if obj is null * * @throws ClassCastException if the object is not * null and is not assignable to the type T. * * @since 1.5 */ public T cast(Object obj) { if (obj != null && !isInstance(obj)) throw new ClassCastException(cannotCastMsg(obj)); return (T) obj; }
4. Summary
This method can only convert objects of the current type or its sub-classes, but simply performs a forced conversion.