0

Everybody knows that before doing any cast we have to check the object type with instanceof, however, with generics the compiler doesn't allow us to check it with generics like this.

if(object instanceof List<Message>)

I was investigating its solution and some people say that we have to check with List only, however, this is not valid for me. I also checked that some developers recommend using isAssignableFrom, but it requires object to have an instance. So how can I check that object is a List of Message (and not a just a list) without creating a trick object?

kalpesh satasiya
  • 799
  • 8
  • 18
  • 3
    You don't *have* to use `instanceof` in order to cast. In fact if you're doing a lot of unknown casts, you most likely have a design flaw that you should fix. – Kayaman Jan 10 '18 at 08:51
  • You should use [PECS](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) when working with generics. This, of course, only works if all elements in the list satisfy the condition/constraint. – Turing85 Jan 10 '18 at 08:53

1 Answers1

0

A bit naive approach

 Object deserializedList = fetchList();
 if (deserializedList instanceof List) {
   for (Object obj : (List)deserializedList) {
     if (obj instanceof Message) {
       Message message = (Message)obj;
       System.out.println("message: " + message);
     } else {
       System.out.println("not a message: " + obj);
     }
   }
 }
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148