Class中的cast方法(强制转换)

来源:互联网 发布:扑克游戏源码 编辑:程序博客网 时间:2024/06/05 21:09

Class中的方法源码:

public T cast(Object obj) {     if (obj != null && !isInstance(obj))          throw new ClassCastException(cannotCastMsg(obj));     return (T) obj;}

测试代码:

@Testpublic void testCast() {    Object worker = new Worker();    //cast方法是就是将参数worker强制转换为其对应的类型    //以下两种方法作用相同    Worker worker1 = Worker.class.cast(worker);    Worker worker2 = (Worker)worker;    System.out.println(worker1.getCountry());}