Cannot get attribute from list <Object> - Servlet

In Class1 , we have a method doGetand a method that returns a list with objects of type Animal.

public List<Animal> getAnimals() 

so I call a method like:

List<Animal> animal = getAnimals();
request.setAttribute("animal_list", animal);

In class 2 , I have a doGet method and I want to take animal_list. My code is:

List<Animal> list500=request.getAttribute("animal_list");

but when I compile, I get a message

"Object cannot be converted to List<Animal>"
+4
source share
1 answer

here you must use from Objectto List<Animal>:

 @SuppressWarnings("unchecked")
 List<Animal> list500= (ArrayList<Animal>)request.getAttribute("animal_list");

request.getAttributeonly returns Object, so you need to determine the exact type with cast. Objectmaybe everything ...

as side node: you get

" Object to ArrayList"

compiler.

" "

annotation. .

+3

Source: https://habr.com/ru/post/1615580/


All Articles