Class: isAssignableFrom(Class cls) : Class « java.lang « Java by API






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

1.Class: forName(String classDec)
2.Class: Annotation[] getAnnotations()
3.Class: getCanonicalName()
4.Class: getClasses()
5.Class: getComponentType()
6.Class: getConstructors()
7.Class: getConstructor(Class...)
8.Class: getDeclaringClass()
9.Class: getDeclaredConstructors()
10.Class: getDeclaredFields()
11.Class: getDeclaredMethods()
12.Class: getDeclaredMethod(String name, Class... parameterTypes)
13.Class: getEnumConstants()
14.Class: getFields()
15.Class: getGenericInterfaces()
16.Class: getGenericSuperclass()
17.Class: getInterfaces()
18.Class: Method getMethod(String name, Class... parameterTypes)
19.Class: getMethods()
20.Class: getModifiers()
21.Class: getName()
22.Class: getPackage()
23.Class: getProtectionDomain()
24.Class: getResource(String name) (absolute from the classpath)
25.Class: getResource(String name) (relative to the class location)
26.Class: getResourceAsStream(String name)
27.Class: getSuperclass()
28.Class: getTypeParameters()
29.Class: isArray()
30.Class: isEnum()
31.Class: isInstance(Object obj)
32.Class: isInterface()
33.Class: newInstance()