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();
}
}
}
List转换为Object后的类型安全问题
最新推荐文章于 2023-02-28 13:47:40 发布