Java Reflection – Class Example

In Java, the classes in your source code are are instances of the java.lang.Class class during runtime. Actually, for every class that you use there is a Class object associated with it. According to the Javadocs, Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

In later post, we will discuss in detail how we can use this Class class for reflection. With it we will be able to determine the properties of a class and find all its fields, methods, interfaces, see if annotations are present, etc.

Common Methods used for Classes

  • getConstructor, getConstructors, getDeclaredConstructor, getDeclaredConstructors, getEnclosingConstructor
  • getMethod, getMethods, getDeclaredMethods
  • getField, getFields, getDeclaredFields
  • getAnnotation, getAnnotations, getDeclaredAnnotations
  • getSuperclass
  • getInterfaces
  • getClasses, getDeclaredClasses
  • getClassLoader
  • getInterfaces
  • getModifiers
  • getPackage
  • getEnumConstants

We can inspect any class and get it’s name using the getClass() method

Getting the Class Name

In order to get the name of a object’s class by using the getName(), getSimpleName(), or getCanonicalName() methods.

System.out.println("Starting ClassExample...");
System.out.println("Name: " +  myString.getClass().getName());
System.out.println("Simple Name: " +  myString.getClass().getSimpleName());
System.out.println("Canonical Name: " +  myString.getClass().getCanonicalName());

Let’s look at the example when using another class, this time let’s look at the Player class.

System.out.println("Player Class Name: " +  player.getClass().getName());
System.out.println("Player Simple Name: " +  player.getClass().getSimpleName());


Getting the Superclass Name

We can gather information about the superclass by using the method getSuperclass(). See the following:

player.getClass().getSuperclass()

Getting the Package Name

We can gather information about its package by using the method getPackage(). See the following:

player.getClass().getPackage()

Dynamic Class loading

So what else can we do with a Class? Well, we can ask it to create a new instance of it’s type of object. Let’s do this using the Player class detailed below. Let’s begin by loading the Player class by name. In order to do this, we will use the forName() static method of Class that returns a class given it’s name as a String.

Class pClass = Class.forName("Player");

COMPILE ERROR

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type ClassNotFoundException

If you tried compiling this from main() you would get an “Unhandled exception type ClassNotFoundException” message. This is due to the fact that ClassNotFoundException is a checked exception which can not be ignored. You will need to wrap this statement in a try/catch construct or add throws clause so that it can be handled elsewhere in the code. Let’s look at the revised code, below.

try {
  Class pClass = Class.forName("Player");
} catch (ClassNotFoundException e) {
  e.printStackTrace();
}

What happened when we tried running this? We got a ClassNotFoundException. Why? Let’s look closer and find out why.

RUNTIME ERROR

java.lang.ClassNotFoundException: Player
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:171)
at com.avaldes.tutorials.ClassExample.main(ClassExample.java:7)

Looking into this further, we notice that we passed Class.forName(“Player”) and we should have given the fully qualified class name to avoid this error message. Let’s look at the revised code.

try {
  Class pClass = Class.forName("com.avaldes.tutorials.Player");
} catch (ClassNotFoundException e) {
  e.printStackTrace();
}

Now the code works. We have now dynamically loaded a class at runtime. But we have not yet instantiated a player object. Let’s do that now. We will create a new instance of player by calling the newInstance() method of the class we just loaded. We will need to add the following code snippet inside the try catch of the previous one.

Creating an instance of class

try {
  Player player = (Player) pClass.newInstance();  
} catch (InstantiationException e) {
  e.printStackTrace();
} catch (IllegalAccessException e) {
  e.printStackTrace();
}

The final code should now look like this:

try {
  Class pClass = Class.forName("com.avaldes.tutorials.Player");
  try {
    Player player = (Player) pClass.newInstance();  
  } catch (InstantiationException e) {
    e.printStackTrace();
  } catch (IllegalAccessException e) {
    e.printStackTrace();
  }
} catch (ClassNotFoundException e) {
  e.printStackTrace();
}

or you have have the final code like this.

Class pClass = null;
Player player = null;

try {
  Class pClass = Class.forName("com.avaldes.tutorials.Player");
} catch (ClassNotFoundException e) {
  e.printStackTrace();
}

try {
  Player player = (Player) pClass.newInstance();  
} catch (InstantiationException e) {
  e.printStackTrace();
} catch (IllegalAccessException e) {
  e.printStackTrace();
}

We will be using the Player class below, for this example.

Java Listing (Player.java)

package com.avaldes.tutorials;

public class Player {
  private String playerName;
  private int startYear;
  private String  team;
  
  public Player(String name, int year, String team) {
    setPlayerName(name);
    setStartYear(year);
    setTeam(team);
  }
  
  public String getPlayerName() {
    return playerName;
  }
  public void setPlayerName(String playerName) {
    this.playerName = playerName;
  }
  public int getStartYear() {
    return startYear;
  }
  public void setStartYear(int startYear) {
    this.startYear = startYear;
  }
  public String getTeam() {
    return team;
  }
  public void setTeam(String team) {
    this.team = team;
  } 

  @Override
  public String toString() {
     return playerName;
  }
}

Let’s try running it now and see what we get…. What? Another error?

RUNTIME ERROR

java.lang.InstantiationException: com.avaldes.tutorials.Player
at java.lang.Class.newInstance0(Class.java:342)
at java.lang.Class.newInstance(Class.java:310)
at com.avaldes.tutorials.Example1.main(Example1.java:9)

We are not able to instantiate the Player class. Let look at the class below. Notice anything missing?
If you look closely we have a constructor in Player class, but it requires three (3) parameters. The newInstance() method requires no-arg default constructor like this. Looking at the class I provided above, you notice this default constructor was missing. Let’s add this in to our Player.java file.

public Player() {
}

Ok, finally working now. Now, let’s finish it up by calling the setter methods using player and adding some nice print statements to see some fancy output on our console. Full program listing include below for your review.

Full Program Listing (ClassExample.java)

package com.avaldes.tutorials;

public class ClassExample {

  public static void main(String[] args) {
    String myString = "This is Java Class Example";
    
    System.out.println("Starting ClassExample...");
    System.out.println("String Class Name...........: " +  myString.getClass().getName());
    System.out.println("String Class Simple Name....: " +  myString.getClass().getSimpleName());
    System.out.println("String Class Canonical Name.: " +  myString.getClass().getCanonicalName());
    System.out.println("String Class SuperClass.....: " +  myString.getClass().getSuperclass());
    System.out.println("String Class Package........: " +  myString.getClass().getPackage());
    
    try {
      Class pClass = Class.forName("com.avaldes.tutorials.Player");
      try {
        Player player = (Player) pClass.newInstance();
        player.setPlayerName("Tom Seaver");
        player.setStartYear(1967);
        player.setTeam("New York Mets");
        
        System.out.println("nPlayer Class Name...........: " +  player.getClass().getName());
        System.out.println("Player Class SuperClass.....: " +  player.getClass().getSuperclass());
        System.out.println("Player Class Package........: " +  player.getClass().getPackage());
        
        System.out.println("nPlayer Details Below...");
        System.out.format("%s, played for the %s, started career in %dn", 
            player.getPlayerName(), player.getTeam(), player.getStartYear());
        
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
}

Full Program Listing (Player.java)

package com.avaldes.tutorials;

public class Player {
  private String playerName;
  private int startYear;
  private String  team;
  
  public Player() {	
  }
	
  public Player(String name, int year, String team) {
    setPlayerName(name);
    setStartYear(year);
    setTeam(team);
  }
  
  public String getPlayerName() {
    return playerName;
  }
  public void setPlayerName(String playerName) {
    this.playerName = playerName;
  }
  public int getStartYear() {
    return startYear;
  }
  public void setStartYear(int startYear) {
    this.startYear = startYear;
  }
  public String getTeam() {
    return team;
  }
  public void setTeam(String team) {
    this.team = team;
  } 

  @Override
  public String toString() {
     return playerName;
  }
}

Output

Starting ClassExample...
String Class Name...........: java.lang.String
String Class Simple Name....: String
String Class Canonical Name.: java.lang.String
String Class SuperClass.....: class java.lang.Object
String Class Package........: package java.lang, Java Platform API Specification, version 1.6

Player Class Name...........: com.avaldes.tutorials.Player
Player Class SuperClass.....: class java.lang.Object
Player Class Package........: package com.avaldes.tutorials

Player Details Below...
Tom Seaver, played for the New York Mets, started career in 1967

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 *