简体   繁体   中英

java cast Object to List<SomeType>

I have some function that requires a List<SomeType> and I have an Object from that I know that it should be of type ArrayList<SomeType> .

How can I test if it really is and how can I cast the object to that type without getting warnings?

something like:

ArrayList<String> testL = new ArrayList<String>();

Object o = testL;
if (o instanceof ArrayList<String>){
  List<String> l = (ArrayList<String>)o;
}

The instanceof check gives an error and the cast gives an [unchecked] warning.

What you are trying to do cannot be achieved by one simple cast. This has to do with type erasure during compilation of Java code. You can do one of two things:

  1. Cast and accept the unchecked warning (you can suppress it by adding @SuppressWarning on the method). Only do this if you are sure that the Object is actual of type List otherwise you will get ClassCastExceptions at runtime.
  2. Check the type of the variable against List and then iterate over it adding each entry to a new list of type T. You can then validate each entry in the original list against type T before adding it. (Not doing so will also result in the unchecked warning)

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