Java Class. cast method, javaclass. cast Method

Source: Internet
Author: User

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.




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.