Reflection API in Java: Purpose & Examples

Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

Like a mirror on our code, Java reflection lets us see what is happening when our Java programs run. This lesson will explain the purpose of reflection in Java and provide examples.

Reflection

The word reflection suggests a mirror, allowing us to look at something. In Java, the concept is quite accurate. Reflections lets you use code to look at code. In Java, the Reflection API (Application Program Interface) can be used to look at a program's code while it runs in the Java virtual machine. But Java's Reflection API is more than a mirror. Not only can you view class/method/field information that is processing as the program runs, but you can actually create instances of classes on the fly.

Purpose

Reflection lets you create instances of new objects or execute methods at run-time without necessarily knowing what objects you are instantiating! It is also a great tool for debugging your program because you can see what is being executed on the fly. The compiler doesn't always catch all errors or mistakes within your code.

Examples

In order to access the tool, you will need to import the Class class in the java utility. Yes, there is a Class for classes! It wouldn't be an object-oriented language without it.


import java.lang.Class;


Let's take a look at some examples of reflection in action.

Get Class Info

Reflection lets us show information about a class. Any object in the Class class (yes that sounds funny, but we are talking about reflection!) is part of your program when it runs. When the program runs, we can use reflection to find out information about that class. In our code we have a simple class:


public class Basic {
  void display() {
    System.out.println("This is a Message!");
 }
}


In the main function of the program, we can use the getClass method from the Class class to display the information.


Basic b = new Basic();
Class showMe = b.getClass();
System.out.println(showMe);


Now that we have the class, we can get the methods.

Get Methods

Reflection lets us discover all of the methods of a given class. If you knew the class name but didn't know the methods, you could write a simple routine to discover them. In order to use this feature of reflection, we have another utility to import: java.lang.reflect.Method. The following code uses reflection to return all methods from the Double class:


import java.lang.Class;
import java.lang.reflect.Method;
public class Reflection {
  public static void main(String[] args) {
   Class dClass = Double.class;
   Method[] methods = dClass.getDeclaredMethods();
   for(Method method : methods) {
    System.out.println("Method name = " + method.getName());
  }
 }
}


Below is a snippet of the output when this code is run. This is very helpful to use for any Java class since you don't have to go hunting for the documentation! You can just reflect on the class and get all the methods.


Java reflection get methods output


We can also use this concept to look at our own classes. Recall the Basic class had a method in it. We can use reflection to display the methods from the Basic class:


import java.lang.Class;
import java.lang.reflect.Method;
public class Reflection {
  public static void main(String[] args) {
   Basic b = new Basic();
   Class showMe = b.getClass();
   Method[] methods = showMe.getDeclaredMethods();
   for(Method method2 : method) {
    System.out.println("Method name = " + method2.getName());
  }
 }
}


When we run the code, the following is displayed:


Java reflection get methods output


We now have a basic understanding of reflection and how it can be used to get class and method information. But it has other powers also. We can create a whole new instance of a class, right at run-time!

Create New Instance of a Class

Before we start creating instances, let's revisit our Basic class:


public class Basic {
  void display() {
   System.out.println("This is a Message!");
  }
}


Next, in the main method, we will try to create a new instance of the Basic class and call the method. If it doesn't exist, an error will be displayed.


public static void main(String[] args) {
  try {
   Class c = Class.forName("Basic");
   Basic b = (Basic) c.newInstance();
   b.display();
  } catch (Exception e) {
   System.out.println("Error: " + e);
  }
}


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support