Using Class.isAssignableFrom method, we can check whether given object is an iterable 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 isIterable(final Class<?> clazz) {
return clazz != null && (Iterable.class.isAssignableFrom(clazz));
}
Above snippet return true, if the given type an iterable, else false.
Find the below working application.
IterableCheckDemo.java
package com.sample.app.collections;
import java.util.Arrays;
import java.util.HashMap;
public class IterableCheckDemo {
public static boolean isIterable(final Class<?> clazz) {
return clazz != null && (Iterable.class.isAssignableFrom(clazz));
}
public static void main(String[] args) {
final Object list = Arrays.asList(2, 3, 5, 7);
final Object map = new HashMap<>();
System.out.println("Is list iterable : " + isIterable(list.getClass()));
System.out.println("Is map iterable : " + isIterable(map.getClass()));
}
}
Output
Is list iterable ? true Is map iterable ? false
You may like
Generic method to concatenate two arrays in Java
Get the string representation of array by given delimiter in Java
Get an iterator from array in Java
No comments:
Post a Comment