Different ways that I can get Class objects in Java using Reflection?

In this tutorial we will explore the various ways we can get the class of objects in Java. In this example, I will show you how to use these four methods.


Get Class Object via the getClass() method

When the instances of classes are available, this method would be the simplest method to employ.

Dog dog = new Dog();
Class dogClass = dog.getClass();
System.out.println(dogClass.getCanonicalName());

Get Class Object via the .class literal

This is one of the easiest way to obtain the Class for primitive and wrapper classes.

Class<?> MyBooleanClass = Boolean.class;
System.out.println(MyBooleanClass.getCanonicalName());

Get Class Object via forName()

If we have qualified names, then we can get the corresponding class via the static method Class.forname(). However, we can not use this method for getting primitive types.

// prints com.avaldes.tutorials.Dog
Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
System.out.println(mc.getCanonicalName());

// prints float[]
Class<?> MyFloatArray = Class.forName("[F");
System.out.println(MyFloatArray.getCanonicalName());

// prints double[][]
Class<?> MyDoubleDimArray = Class.forName("[[D");
System.out.println(MyDoubleDimArray.getCanonicalName()); 

Get Class Object via TYPE field in wrapper classes

Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.
Using that information, we can get a class object for each object we need.

// prints boolean
Class<?> MyboolClass = Boolean.TYPE;
System.out.println(MyboolClass.getCanonicalName()); 

// prints int
Class<?> MyintClass = Integer.TYPE;
System.out.println(MyintClass.getCanonicalName()); 

// prints char
Class<?> MyChar = Character.TYPE;
System.out.println(MyChar.getCanonicalName()); 

Full Program Listing

package com.avaldes.tutorials;

public class InstantiateClassExample {

  public static void main(String[] args) throws 
      ClassNotFoundException, InstantiationException, IllegalAccessException {
    
    System.out.println("Get classes via runtime class loading...");
    Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
    Dog fido = (Dog) mc.newInstance();
    System.out.println(mc.getCanonicalName()); // prints com.avaldes.tutorials.Dog
    
    System.out.println("\nGet classes via getClass() method...");
    Dog dog = new Dog();
    Class dogClass = dog.getClass();
    System.out.println(dogClass.getCanonicalName()); // prints com.avaldes.tutorials.Dog
        
    //----- Get classes for primitives -----
    System.out.println("\nGet classes for primitives...");
    Class<?> MyboolClass = Boolean.TYPE;
    System.out.println(MyboolClass.getCanonicalName()); // prints boolean
    
    Class<?> MyintClass = Integer.TYPE;
    System.out.println(MyintClass.getCanonicalName()); // prints int
    
    Class<?> MyChar = Character.TYPE;
    System.out.println(MyChar.getCanonicalName()); // prints char
    
    //----- Get classes for wrapper classes -----
    System.out.println("\nGet classes for wrapper classes...");
    Class<?> MyStringClass = String.class;
    System.out.println(MyStringClass.getCanonicalName()); // prints java.lang.String
    
    Class<?> MyIntegerClass = Integer.class;
    System.out.println(MyIntegerClass.getCanonicalName()); // prints java.lang.Integer

    Class<?> MyBooleanClass = Boolean.class;
    System.out.println(MyBooleanClass.getCanonicalName()); // prints java.lang.Boolean

    //----- Get classes for all array types -----
    System.out.println("\nGet classes for array types...");
    Class<?> MyByteArray = Class.forName("[B");
    System.out.println(MyByteArray.getCanonicalName()); //prints byte[]

    Class<?> MyFloatArray = Class.forName("[F");
    System.out.println(MyFloatArray.getCanonicalName()); //prints float[]
    
    Class<?> MyDoubleArray = Class.forName("[D");
    System.out.println(MyDoubleArray.getCanonicalName()); //prints double[]

    Class<?> MyLongArray = Class.forName("[J");
    System.out.println(MyLongArray.getCanonicalName()); //prints long[]
    
    Class<?> MyDoubleDimArray = Class.forName("[[D");    // two-dimensional array
    System.out.println(MyDoubleDimArray.getCanonicalName()); //prints double[][]
  }
}

Full Program Listing (Dog.java)

package com.avaldes.tutorials;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME) 
@interface Detail {
  String description();
}

@Retention(RetentionPolicy.RUNTIME) 
@interface Tag {}

public class Dog extends Mammal implements Animal {
  public Dog() {
  }
  
  public Dog(String name) {
    setName(name); 
  }
  
  public Dog(String name, boolean hair) {
    this.setName(name);
    this.setHair(hair);
  }
  
  @Override
  public void eat() {
    System.out.println("Dog is eating...");
  }

  @Override
  public void sleep() {
    System.out.println("Dog is Sleeping...");
  }

  @Override
  public void walk() {
    System.out.println("Dog is Walking...");
  }
  
  @Tag
  public void Bark() {
    System.out.println("Dog is Barking...");
  }
  
  @Tag
  @Detail(description = "Display private secret message")
  private void tellASecret() {
    System.out.println("All dogs go to Heaven...");
  }
  
  public class PublicInnerClass {}
  private class PrivateInnerClass {}
  protected class ProtectedInnerClass {}
  class DefaultInnerClass {}
}

Output

Get classes via runtime class loading...
com.avaldes.tutorials.Dog

Get classes via getClass() method...
com.avaldes.tutorials.Dog

Get classes for primitives...
boolean
int
char

Get classes for wrapper classes...
java.lang.String
java.lang.Integer
java.lang.Boolean

Get classes for array types...
byte[]
float[]
double[]
long[]
double[][]

Java Reflection Examples

  • Class Example
    Simple example shows you how to dynamically load and instantiate a class, get class name, package name, and superclass name.
  • Modifier Example
    Showing you how to get information about classes, fields and methods using modifier method.
  • Method Example
    Providing full details of how to get all methods, and invoke methods using reflection.

Frequently Asked Questions on Java Reflection API (FAQs)

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *