How to return a List inside this bounded generic method?

大兔子大兔子 提交于 2021-02-10 20:14:21

问题


I have class Response

public class Response<T extends ResponseData> {
    private final T data;
    //other fields, getters, setters ...
}

and the empty interface ResponseData:

public interface ResponseData {
}

It takes any object as data but this object must implement the "empty" interface which I created just to force all classes returned inside "data" element be of same super type

Now the problem is that I need to return a List inside the data element, but:

  1. I don't find it clean to create a ResponseData implementation which serves only as a wrapper around my List

  2. I can't return the List directly because it doesn't belong to my code and therefore I can't make it implement the marker interface (ResponseData)

So is there a solution to my problem other than the one that says I should delete the marker interface and allow any object to be returned in the data element?

n.b. : My purpose of the marker interface is to make any created classes which will be returned inside the data element inside the response,for anyone who reads them, clear towards their purpose of existence

n.b. : As mentioned in number 1 above, I know that this solution exists:

class ResponseDataWrapper implements ResponseData{
    private final List<SomeType> responseList;
    
    //getters,setters
}

but it is not clean as in this case there is a layer of nesting (i.e. the wrapper class) which is not necessary between the List and the "data" element in the response


回答1:


Have a response object like this that Returns the list:

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class SomeCoolResponseForAnApi implements ResponseData{
    private List<SomeObject> theListYouWantToReturn;

    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    @Data
    public static class SomeObject{
        private String name;
        private String age;
    }
}

PS: I have used lombok, you can just use regular getters and setters.



来源:https://stackoverflow.com/questions/64299778/how-to-return-a-list-inside-this-bounded-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!