Home » Java » java – How to convert a generic Object to List<Entity> with no unchecked cast warning on JDK 11-Exceptionshub

java – How to convert a generic Object to List<Entity> with no unchecked cast warning on JDK 11-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Let’s say I have an Object parameter on a method, I’d like to cast it on a List using lambda.

This is my code, I’m using JDK 11:

Optional.ofNullable(myobject).map(o -> (List<MyEntity>)o).ifPresent(o -> {
   // should be ok, however, I get an unchecked cast warning because of (List<String>)o
});

Actually I could also do the follow, but I loose reference to MyEntity:

Optional.ofNullable(myobject).map(List.class::cast).ifPresent(o -> {
   // Simply converted to a generic List
});

Any hints?

How to&Answers: