简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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