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

Class中的方法源码:

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

测试代码:

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

你可能感兴趣的:(java)