1. Java API
Public T cast (Object obj);
Casts an object to the class or interface represented
The explanation is more general, meaning to replace an object with a class or interface.
2. code example
/*** Created by Shengke on 2016/10/22.*/classA { Public Static voidShow () {System.out.println ("Class A Show () function"); }}classBextendsA { Public Static voidShow () {System.out.println ("Class B Show () function"); }} Public classTestcast { Public Static voidMain (string[] args) {testcast cls=NewTestcast (); Class C=Cls.getclass (); System.out.println (c); Object obj=NewA (); B B1=NewB (); B1.show (); //Casts ObjectA A =NewA (); A= A.class. Cast (B1); System.out.println (Obj.getclass ()); System.out.println (B1.getclass ()); System.out.println (A.getclass ()); }}
Execution results
Class Com.scot.effective.genericity.TestCastClass B Show () Functionclass Com.scot.effective.genericity.Aclass Com.scot.effective.genericity.Bclass com.scot.effective.genericity.b
The core is: a = A.class. Cast (B1); Convert A to Type B, where it is easy to create a misunderstanding of B1 into a type.
3. Source code
/*** Casts an object to the class or interface represented * by this {@codeClass} object. * * @paramobj The object to be cast *@returnthe object after casting, or null if obj is null * *@throwsClassCastException if the object is not * null and was not a assignable to the type T. * * @since1.5*/ PublicT cast (Object obj) {if(obj! =NULL&&!isinstance (obj))Throw Newclasscastexception (cannotcastmsg (obj)); return(T) obj; }4. Summary
This method can only convert objects under the current type or its subclasses, but simply makes a strong move.
Java Class.cast method