I am working on a project that requires passing around objects, what I am trying to do, is turn that object back into a Map like so.
Object o = new Map<String, String>();
Map<String,String> map = (Map<String,String>)o;
This seems to work as expected, but I am getting a
Type safety: Unchecked cast from Object to Map
I know that I could use @SuppressWarnings("unchecked")
, but I would prefer to do it in a way that I don't have a warning. How would this be done?
You can check, if o
is a Map
with o instanceof Map
. But you can't check the Generic Arguments <String,String>
, since they're erased at runtime. So even with the instanceof
check you'll get a warning.
Since Map
extends Object
, you can just use a Map
reference instead of downcasting to Object
.
So in your code, simply replace
Object o = new Map<String, String>();
with
Map<String, String> o = new Map<>();
And then your second line (with the unchecked cast) becomes unnecessary.
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.