Java Class.cast方法

1、Java api

public T cast(Object obj);

Casts an object to the class or interface represented

解释的比较笼统,意思就是将一个对象装换为类或者接口。

2、代码示例

/**
 * 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());
    }
}

执行结果

class com.scot.effective.genericity.TestCast
Class B show() function
class com.scot.effective.genericity.A
class com.scot.effective.genericity.B
class com.scot.effective.genericity.B  
核心为:a = A.class.cast(b1); 把a转化为了B类型,此处容易产生把b1转成A类型误解。

3、源码

    /**
     * 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、总结

此方法只能转换当前类型或其子类下的对象,只是简单进行强转。




转载于:https://www.cnblogs.com/shengkejava/p/5988814.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值