Java Class.cast method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.