Copyright

Reflection in Java: Examples & Mechanism

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.

One of the powerful features of Java is the ability to write code that acts as a mirror, showing us run-time features of the code. This lesson will explain reflection and provide code examples.

Reflection

Java allows reflection, that is the code you write so that you can view and change behavior at run-time. Think of it as a mirror. You don't see that spot on your tie until you see it in the mirror. The same can be applied to reflection. Java can see the information about a class even though it might not be accessible when the program is running.

Before we pull out the mirror, let's build a little class that we can use for our experiments. The following code sets up a class for green tea, including some variables and methods to get and set values.


SELECT emp.empID, emp.empName
FROM employee
 (SELECT planCode, COUNT(empID) as emp_count
  FROM benefits
  GROUP BY plancode) subquery 1
WHERE subquery1.empID = employee.empID;
public class GreenTea {
  private double caffeine;
  private String blend;
  public double totalCaffeine;
  public GreenTea(int code) {
   if(code == 25) {
    blend = "Dragonwell"
    caffeine = 42.58;
   }
   if(code == 30) {
    blend = "Zen";
    caffeine = 29.5;
   }
  }
  public double getCaffeine() {
   return caffeine;
  }
  public String getClend() {
   return blend;
  }
  public void setCaffeine(double caffeine) {
   this.caffeine = caffeine;
  }
  public String setBlend(String blend) {
   this.blend = blend;
  }
  public void calcValues(double oz) {
   totalCaffeine = oz * caffeine;
   System.out.println("Total caffeine = " + totalCaffeine);
  }
}


There's a lot of code here, but we will be using reflection to find (and change) some of these pieces.

Get the Name of a Class

Before we can do anything with reflection, we will need to import the core Java utility that lets us do this. Java's reflection methods are in the java.lang.reflect package. To use them we place the following import statement before any class that will use these methods:


import java.lang.reflect.*;


The first thing we will do is retrieve some information about the GreenTea class, both its object name and the true name of the class.


//get the class object
Class green = GreenTea.class;
System.out.println(green);


When this code runs, the following output is displayed:


Java reflection class name output


We have one more option that might make more sense. Instead of the long names being displayed, we can also get the simple name of the class. So, what name did we actually give it? The reflection method includes the getSimpleName method:


//Simple name
String greenTeaSimple = green.getSimpleName();
System.out.println("Simple Name = " + greenTeaSimple);


Now the output is much cleaner and gives us a more understandable name of the class:


Java reflection get simple output


Get Methods

We can use reflection to get the methods of a class. There is a method to get methods (like a committee to review committees!) called getMethods(). This works, but it also returns any system-defined methods in a class. We don't necessarily need those for this lesson. Instead, we can focus only on the methods we actually declared in our code. Recall we had three methods, get caffeine, get blends, and set the total caffeine level.

In the following code, we will use the getDeclaredMethods() method to get the methods that we defined. The 'for' loop steps through the methods and returns the value, using the getName() method.


//get all methods
Method[] gtMethods = green.getDeclaredMethods();
//loop through the methods
for(Method method : getMethods) {
  System.out.println("Method = " + method.getName());
}


When the code runs, we get the following output:


Java reflection get methods output


Now that we have the methods, let's try looking at the fields.

Get Fields

This is the part that makes reflection a little dangerous. Remember that Java is great at data hiding. It can protect variables as private, thus protected from other members of the class. Reflection lets you break down that barrier and access private members of a class. This is why you would not update these fields with reflection.

That said, let's look at how we can access members of a class. The following code uses the getDeclaredFields method to return all fields in our GreenTea class. Because we are using reflection, it doesn't matter that they are private! In fact, you'll notice another line of code that highlights the reason that we don't do this on live production. It is easy to circumvent Java's data protection methods.


Class green = GreenTea.class;
Field[] fields = green.getDeclaredFields();
for(Field oneField: fields) {
  Field field = green.getDeclaredField("blend");
  String gtFieldName = field.getName();
  System.out.println("Field = " + getFieldName);
//don't do this on Production!
  field.setAccessible(true);
}


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