NoobProg
NoobProg

Reputation: 91

How to get the values of specific fields in a Map<String, Object>

I have something like:

Map<String, Object> hashMap;

When I do something like:

hashMap.get("binary"), I get value as: {size=5642, name=abc}

Here key is binary and value is an Object of Type Object and is {size=5642, name=abc}

Note the values dont belong to a particular class. In Python I can do something like hashMap["binary"]["size"], was wondering what would be the equivalent in java

How do I get the value of size directly without parsing the above string?

Upvotes: 0

Views: 7396

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42461

The value is not of Type Object, but of some type that extends from Object (in java everything extends Object implicitly). Let's call it "X"

Now, it doesn't work like python because unlike python java doesn't have that dynamic nature.

{size=5642, name=abc} is probably a string representation of that type X. This is what you see in a debugger or maybe when trying to print the value on console with System.out.println or something.

Now first of all figure out which type is it:

Object value = hashMap.get("binary")
System.out.println(value.getClass().getName());

It will print the class name

Then check the source of that class, probably it looks like this:

public class X {
   private final int size;
   private final String name;

   ... // constructor, other stuff maybe


   // these are called "getters" in java world
   public int getSize() {return size;}
   public String getName() {return name;}
}

From that point you have 2 ways to get the size:

Object value = hashMap.get("binary");
int size = ((X)value).getSize();  // This is called downcasting

The drawback of this method is that you don't utilize the power of generics

So the better option is a refactoring if its possible of course:

Map<String, X> hashMap = ...
X value = hashMap.get("binary");
value.getSize();

One final note:

If it happens that the value is of type String, you won't be able to get the size other than parsing the value with regular expression or something. In this case consider a refactoring as a better option.

Upvotes: 2

Related Questions