简体   繁体   English

用Java中的泛型过滤集合

[英]Filtering collection with 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 . 和一个Collection<Client> filteredClients

I get an Object: 我得到一个对象:

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

I need to filter from response object, which could be one of the above collection type, the clients that do not appear in filteredClients. 我需要从响应对象(可能是上述集合类型之一)中进行过滤,这些客户端不会出现在filteredClients中。

Is there a clean way to do it? 有没有一种干净的方法?

GenericMessage looks like this: GenericMessage看起来像这样:

public class GenericMessage<T> {
   T object;

   public T getObject(){
    return object;
   }
   public void setObject(T object){
    this.object = object;
   }
}

Client looks like this: 客户看起来像这样:

public class Client extends Base

SearchResponse looks like this: SearchResponse看起来像这样:

public class SearchResponse<T> extends Base{
   List<T> results;

   public List<T> getResults() {
        return results;
   }

    public void setResults(List<T> results) {
        this.results = results;
   }
}
 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?
      }
 }

What John B wrote or adding the class type parameter to the GenericMessage class. John B编写的内容或将类类型参数添加到GenericMessage类的内容。

Something like: 就像是:

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

public Class<?> getType() {
    return type;
}

And later on, you can filter on this value: 然后,您可以过滤该值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM