Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make method return class wrapping generic

A class has a similar type of method (let’s call it a collector). I think these methods can be a method by making it return a class wrapping generic values.

This is example code

public class Collector {
    RestTemplate restTemplate = new RestTemplate();

    /*I want to make method like this without making the Collector Class with generic value */
    public APICallResultDto<T, V> collectData() {
        APICallResultDto<T, V> result = new APICallResultDto<>();

        /* boiler plate
        * (1) complete request url
        * (2) call api
        * (3) validate response
        * (4) transform data
        * */

        return result;
    }

This code produce errors Cannot resolve symbol 'T' & Cannot resolve symbol 'V'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know I can solve this problem by making Collector class with generic values. I want to Collector class to be singleton, I mean the bean. So I can’t do that.

Is there any way?

>Solution :

It will compile if you add <T, V> in front of return type, as shown below:

public <T, V> APICallResultDto<T, V> collectData() {
    //...
}

For reference: Generic Methods

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading