Maurice
Maurice

Reputation: 7381

How can i do an instanceof check on a generics type list?

I am writing a method that can take different lists of 3 different objects that each extend the same superclass. The method signature looks like this:

private void writeObjectToCsv(File file, List<? extends ZohoData> rawDataView)

I need to know which list has been passed as a parameter so I want to use an instanceof check like so:

if (rawDataView instanceof List<ZohoChatData>)

However this gives me an error that says 'illegal generic type for instanceof'(ZohoChatData is marked red in the IDE). ZohoChatdata extends ZohoData so I don't understand why the compiler is giving me this error. Does anyone know?

Thank you.

Upvotes: 2

Views: 1750

Answers (2)

ganesan dharmalingam
ganesan dharmalingam

Reputation: 1223

Generics is used only compile time the type will be erased after compilation and it will be no more at runtime. The instanceof is used to check the type of the object. So you cannot use instanceof in a Generic type class like List. To determine what type of object the list contains the ways explained by gem is good enough.

Upvotes: 1

semvdwal
semvdwal

Reputation: 215

I've had this issue in the past and found two possible ways to solve it:

  1. Add the runtime class to the method signature or to the class which holds the method so you know which type you're using at runtime.
  2. Check the list size and if it has one item, get that item and check it's type.

Also, you can move the type check to the part where the item is processed / used altogether. This would remove the issue too.

Regards,

Sem

Upvotes: 0

Related Questions