在Class1中,我们有一个方法doGet和一个返回List的方法,该类包含类型为Animal的对象.
public List getAnimals()
所以我称之为方法:
List animal = getAnimals();
request.setAttribute("animal_list", animal);
在Class 2中我也有一个方法doGet,我想采取animal_list.我的代码是:
List list500=request.getAttribute("animal_list");
但是当我编译时,我得到了消息
"Object cannot be converted to List"
解决方法:
从对象到列表< Animal>的强制转换这里有必要:
@SuppressWarnings("unchecked")
List list500= (ArrayList)request.getAttribute("animal_list");
request.getAttribute只返回Object,因此你必须通过强制转换来定义确切的类型.对象可能就是一切……
作为一个副节点:你会得到一个
“Unchecked cast from Object to ArrayList”
来自编译器的警告.在这种情况下,您可以添加
“suppress the warning”
注解.之后警告将消失.
标签:java,attributes,servlets,get
来源: https://codeday.me/bug/20190628/1314211.html