ClassCastException occurs in the extended for statement.How do I fix the Id of each Student object to the console so that there are no errors?Thank you.
■ Test class
@ Controller
public class test {
@RequestMapping(value="/login", method=RequestMethod.GET)
public String login(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
RestTemplate restTemplate = new RestTemplate();
@SuppressWarnings ("unchecked")
List<Student>aiu=restTemplate.getForObject("http://localhost:9292/student?userId=00002", List.class);
for (Student a:aiu) {
System.out.println(a.getId());
}
return "login";
}
}
■ Student Class
public class Student {
private String id;
private String name;
private String score;
public String getId() {
return id;
}
public void setId(String id){
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score){
This.score=score;
}
}
■ StudentController Class
@RestController
public class StudentController {
@RequestMapping(value="/student", method=RequestMethod.GET)
publicList<Student>get(@RequestParamStringuserId){
List<Student>a=new ArrayList<Student>();
Student aa = new Student();
aa.setId("0001");
aa.setName("Ando");
aa.setScore("30");
Student ab = new Student();
ab.setId("0002");
ab.setName("Tanaka");
ab.setScore("48");
a.add(aa);
a.add(ab);
return a;
}
}
The code below does not specify a list type, so
I think the element will be Object and ClassCastException will occur.
List<Student>aiu=restTemplate.getForObject("...", List.class);
If you receive it in a Student array as follows,
ClassCastException will no longer occur.
ResponseEntity<Student[]>responseEntity=
restTemplate.getForEntity(url, Student[].class);
Student [] aiu=responseEntity.getBody();
© 2024 OneMinuteCode. All rights reserved.