Reputation: 7381
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
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
Reputation: 215
I've had this issue in the past and found two possible ways to solve it:
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