Filtering a collection using generics in java

I have the following type of collection:

Collection<GenericMessage<Collection<Client>>>; Collection<GenericMessage<Client>>; Collection<GenericMessage<SearchResponse<Client>>>; 

and a Collection<Client> filteredClients .

I get an object:

 Collection<GenericMessage<?>> resObject = (Collection<GenericMessage<?>>) response.getEntity(); 

I need to filter from the response object, which may be one of the above types of collections, clients that do not appear in the filters.

Is there a clean way to do this?

GenericMessage is as follows:

 public class GenericMessage<T> { T object; public T getObject(){ return object; } public void setObject(T object){ this.object = object; } } 

The client is as follows:

 public class Client extends Base 

SearchResponse is as follows:

 public class SearchResponse<T> extends Base{ List<T> results; public List<T> getResults() { return results; } public void setResults(List<T> results) { this.results = results; } } 
+4
source share
2 answers
  if (!resObject.isEmpty()){ GenericMessage<?> firstMessage = resObject.iterator().next(); Object first = firstMessage.getObject(); if (first instanceof Client){ // do Client stuff }else if (first instanceof SearchResponse){ // do SearchResponse }else if (first instanceof Collection){ // blah }else{ // error? } } 
+2
source

What John B wrote or added a type class parameter to the GenericMessage class.

Sort of:

 GenericMessage(Class<?> type) { this.type= type; } public Class<?> getType() { return type; } 

And later you can filter this value:

 if (getType().equals(Client.class)) { ... //do whatevs } else if ... 
0
source

Source: https://habr.com/ru/post/1485815/


All Articles