1. 程式人生 > >Class中的cast方法(強制轉換)

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