Friday 11 November 2022

How to check the type or object is a map or not?

Using Class.isAssignableFrom method, we can check whether given object is a map or not.

 

Signature

public native boolean isAssignableFrom(Class<?> cls)


'isAssignableFrom' method return true, if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter, else false.

 

Example

public static boolean isMap(final Class<?> clazz) {
	return clazz != null && (Map.class.isAssignableFrom(clazz));
}

 

Above snippet return true, if the given type a map, else false.

 


Find the below working application.

 

MapCheckDemo.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class MapCheckDemo {

	public static boolean isMap(final Class<?> clazz) {
		return clazz != null && (Map.class.isAssignableFrom(clazz));
	}

	public static void main(String[] args) {
		final Object obj1 = Arrays.asList(2, 3, 5, 7);
		final Object obj2 = new HashMap<>();

		System.out.println("Is obj1 map : " + isMap(obj1.getClass()));
		System.out.println("Is obj2 map : " + isMap(obj2.getClass()));
	}

}

 

Output

Is obj1 map : false
Is obj2 map : true

 

   

You may like

Interview Questions

Collection programs in Java

Array programs in Java

How to check the object is an iterable or not?

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

No comments:

Post a Comment