Class: isAssignableFrom(Class> cls)
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Main {
public static boolean isNumber(final Class dataType) {
return Number.class.isAssignableFrom(dataType);
}
public static void main(final String[] args) {
final Set classes = new HashSet();
classes.add(Class.class);
System.out.println("Using isAssignableFrom:");
useAssignable(classes);
System.out.println("\nUsing isInstance:");
useIsInstance(classes);
}
public static void useAssignable(final Set inputSet) {
final Iterator iter = inputSet.iterator();
Object obj = null;
while (iter.hasNext()) {
obj = iter.next();
if (obj != null) {
if (Number.class.isAssignableFrom(obj.getClass())) {
System.out.println(obj);
}
}
}
}
public static void useIsInstance(final Set inputSet) {
final Iterator iter = inputSet.iterator();
Object obj = null;
while (iter.hasNext()) {
obj = iter.next();
if (Number.class.isInstance(obj)) {
System.out.println(obj);
}
}
}
public static void useIsInstance2(final Class dataType, final Set inputSet) {
if (dataType == null) {
throw new NullPointerException();
}
final Iterator iter = inputSet.iterator();
Object obj = null;
while (iter.hasNext()) {
obj = iter.next();
if (dataType.isInstance(obj)) {
System.out.println(obj);
}
}
}
}
Related examples in the same category