Home > Software design >  ParameterizedTypeReference cannot be instantiated when using with RestTemplate to get a ResponseEnti
ParameterizedTypeReference cannot be instantiated when using with RestTemplate to get a ResponseEnti

Time:01-19

My SpringBoot controller has a method:

@GetMapping("/all-quotes")
public List<Encouragement> allQuotes() {
    return encouragementService.allQuotes();
}

I wanted to get a ResponseEntity<List<Encouragement>> and was trying the approach in this SO https://stackoverflow.com/a/50540909/398348

However the compiler complains that ParameterizedTypeReference is an abstract class and cannot be instantiated. How are they able to instantiate it?

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class EncourageApplicationIntegrationTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void contextLoads() {
        ResponseEntity<List<Encouragement>> responseEntity;
        responseEntity = restTemplate.getForEntity("/all-quotes", new ParameterizedTypeReference<List<Encouragement>>());
    }
}

CodePudding user response:

You are missing curly braces in ParameterizedTypeReference

It should be like this

new ParameterizedTypeReference<List<Encouragement>>(){}
  • Related