Hasnain Ali Bohra
Hasnain Ali Bohra

Reputation: 2180

Why in Groovy Map.class returns null?

I have a simple piece of code in Groovy:

ErrorInfoVO vo = new ErrorInfoVO();
Object obj1 = vo;
System.out.println(obj1.class.getName());
System.out.println(obj1.getClass().getName());

Map map = new HashMap()
Object obj2 = map
System.out.println(obj2.getClass().getName());
System.out.println(obj2.class.getName());

The output is:

com.vo.ErrorInfoVO
com.vo.ErrorInfoVO
java.util.HashMap
Exception in thread "main" java.lang.NullPointerException:

Why obj2.class is returning the null ?

Upvotes: 3

Views: 1342

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

You get NullPointerException because

obj2.class

does not translate to

obj2.getClass()

but rather to

obj2.get("class")

This is because obj2 in your case example is of type Map and you use property notation. It means that obj2.class returns a value associated with a key named class, and a key-value entry associated with such key does not exist in your map, so it returns null. Then you call a getName() method on and you get NullPointerException.

This use case is described in the Groovy documentation page Working with collections, 2.2. Map property notation:

Note: by design map.foo will always look for the key foo in the map. This means foo.class will return null on a map that doesn’t contain the class key. Should you really want to know the class, then you must use getClass():

def map = [name: 'Gromit', likes: 'cheese', id: 1234]
assert map.class == null
assert map.get('class') == null
assert map.getClass() == LinkedHashMap // this is probably what you want

Upvotes: 7

Related Questions