List轉換爲Object後的類型安全問題

import com.teriste.java8.entity.Department;
import com.teriste.java8.entity.Employee;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class GenericListTest
{
    @Test
    public void testConvertGeneric(){
        List<Department> deptList=new ArrayList<>();
        Department department=new Department();
        department.setDeptId("111");
        deptList.add(department);
        Object obj=deptList;
        //List轉換爲Object後失去了編譯期的泛型類型檢查,因此再強轉爲List時不會出現語法錯誤
        List<Employee> empList=(List)obj;
        try{
            //因此在運行期使用轉換後的list時不能確定是類型安全的,需要做異常處理
            empList.forEach((e)->System.out.println(e));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章