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

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