简体   繁体   中英

How can I check what type of data a java map contains?

I've got a generic map in some java code that can contain, for a specific field, either a String or an Array, but I'm pretty new to Java and am not quite sure how to distinguish between the two.

My current idea is to write a class with an overloaded method that will do different things with the two data types, but what I'd really like to do is to use something like typeof from javascript to controll an if statement, rather than creating a whole new class.

Is there such a thing in Java? And is there a better way to do this? I'm getting the array out of code I have no control over, so changing the map isn't an option.

Your map contains objects. You can test the type of an object with instanceof .

For example:

 Object value = map.get( key );
 if ( value instanceof String ) {
     ...
 }
 else if ( value instanceof Object[] ) {
     ...
 }

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