0

I'm working on a Java project, and I want to pass a Java object to a method in order to avoid code duplication. This is my code :

private List<Dog> getListDogs(SearchResponse response) {

    SearchHit[] searchHit = response.getHits().getHits();

    List<Dog> dogList = new ArrayList<>();

    if (searchHit.length > 0) {

        Arrays.stream(searchHit).forEach(hit -> dogList.add(objectMapper.convertValue(hit.getSourceAsMap(),Dog.class))
                );
    }

    return dogList;
}

I have other objects that need to use the same method like Cat Object and Horse object. Do you have any idea on how I can make my method generic in order to pass just the object type as a parameter?

Something like this:

private List<Generic> getListObject(SearchResponse response , GenericObject object){...
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
James
  • 1,190
  • 5
  • 27
  • 52
  • This may help: https://stackoverflow.com/questions/450807/how-do-i-make-the-method-return-type-generic – Gus Oct 26 '20 at 15:26
  • Like `private List getListObject(SearchResponse response , Class clazz){...` – Eklavya Oct 26 '20 at 15:29
  • @Eklavya-UpvoteDon'tSayThanks for your response , but how i can remplace Animal.class and List with my new parameter Class clazz – James Oct 26 '20 at 15:31

1 Answers1

0

Following the comments above, I found out how to resolve my problem, and this is the generic method code:

private <T> List<T> getSearchResult(SearchResponse response , Class<T> clazz) {

    SearchHit[] searchHit = response.getHits().getHits();

    List<T> lisOfObjects = new ArrayList<>();

    if (searchHit.length > 0) {
             Arrays.stream(searchHit).forEach(hit -> lisOfObjects.add(objectMapper.convertValue(hit.getSourceAsMap(),clazz)));
    }

    return lisOfObjects;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
James
  • 1,190
  • 5
  • 27
  • 52