java 从 HttpSession 检索 ArrayList 时获取无法将对象转换为 ArrayList 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1755847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting cannot convert object to ArrayList error when retrieving ArrayList from HttpSession
提问by Ankur
I have saved an ArrayList to the session object. I am trying to retrieve it using
我已经将一个 ArrayList 保存到会话对象中。我正在尝试使用
sriList = session.getAttribute("scannedMatches");
I am getting the compile time error "Cannot convert from Object to ArrayList". How can I get my ArrayList back from the session object.
我收到编译时错误“无法从对象转换为 ArrayList”。如何从会话对象中取回我的 ArrayList。
回答by Pascal Thivent
The HttpSession#getAttribute()method returns java.lang.Object:
该HttpSession#getAttribute()方法返回java.lang.Object:
public java.lang.Object getAttribute(java.lang.String name)
Did you try to cast the returned object?
您是否尝试投射返回的对象?
sriList = (ArrayList)session.getAttribute("scannedMatches");
回答by Vincent Ramdhanie
You have to cast it.
你必须投它。
sriList = (ArrayList)session.getAttribute("scannedMatches");
回答by Rakesh Juyal
try this:
试试这个:
Object scannedMatchesObj = session.getAttribute("scannedMatches");
if ( scannedmatchesObj instanceOf List ){
sriList = (ArrayList)scannedMatchesObj;
//Do your stuff...
}

