Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Using Reflection API to determine whether class object is a primitive type or not

Program to demonstrate how Reflection API can be used to determine whether a class object is a primitive type or not in Java

package com.hubberspot.reflection;

public class PrimitiveInfo {

   public static void main(String[] args) {

 // Create Class instance by
 // *primitive.class as its instance
 Class intClass = int.class;
 Class longClass = long.class;
 Class byteClass = byte.class;
 Class shortClass = short.class;
 Class floatClass = float.class;
 Class doubleClass = double.class;
 Class charClass = char.class;
 // void.class is a primitive type 
 Class voidClass = void.class;
 // Create Class instance by
 // *non-primitive.class as its instance
 Class stringClass = String.class;
 Class objectClass = Object.class;

 System.out.println("Primitive Testing Starts .... ");
 System.out.println("-------------------------------------------");
 System.out.println();

 primitiveType(intClass);
 primitiveType(longClass);
 primitiveType(byteClass);
 primitiveType(shortClass);
 primitiveType(floatClass);
 primitiveType(doubleClass);
 primitiveType(charClass);
 primitiveType(voidClass);
 primitiveType(stringClass);
 primitiveType(objectClass);

 System.out.println();
 System.out.println("Primitive Testing Ends .... ");
 System.out.println("-------------------------------------------");

   }

   public static void primitiveType(Class primitive){
        // isPrimitive() method checks whether Class reference is of 
        // primitive type or not 
 if(primitive.isPrimitive()){
  System.out.println(primitive.getName() + " is a primitive type");
 }else{
  System.out.println(primitive.getName() + " is not a primitive type");
 }
   }

}




Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot