Home » Core Java » reflection » Java Reflection Example

About Konstantina Dimtsa

Konstantina Dimtsa
Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java Reflection Example

Java Reflection provides the ability to inspect and modify the runtime behavior of applications. Using reflection we can inspect a class or an interface, get their constructors, methods and fields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values. The classes of Reflection API are part of the package java.lang.reflect and the methods of Reflection API are parts of the package java.lang.Class.

1. Java Reflection API

Before we use the capabilities offered by Reflection API, we must first obtain the java.lang.Class object of the class. If we know the name of the class at compile time, we can do the following:

Class object = classObject.class;

After the creation of the class object, we can use any method of the java.lang.Class package according to our needs.

  • Common methods of java.lang.Class

    • String getName()
      Returns the full name of the entity represented by this Class object, as a String.
    • String getSimpleName()
      Returns the simple name of the underlying class as given in the source code.
    • Package getPackage()
      Gets the package for this class.
    • Constructor<T>[] getConstructors()
      Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
    • Constructor<T> getConstructor(Class<?>... parameterTypes)
      Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
    • Method[] getDeclaredMethods()
      Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.
    • Method[] getMethods()
      Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
    • Field[] getFields()
      Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
    • Field getField(String name)
      Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

For further information, you can have a look at java.lang.Class API.

  • Common methods of java.lang.reflect.Constructor

    Using Java Reflection API we can inspect the constructors of classes and instantiate objects at runtime. The obtaining of constructor object is achieved by the perspective methods of the class java.lang.reflect.Constructor.
    Specifically, for the instantiation of an object we use the following method:

    • T newInstance(Object... args)
      Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters.

For further information, you can have a look at java.lang.reflect.Constructor API.

  • Common methods of java.lang.reflect.Method

    Using Java Reflection API we can inspect the methods of classes and invoke them at runtime. This is achieved by using the Java class java.lang.reflect.Method.

    • String getName()
      Returns the name of the method represented by this Method object, as a String.
    • Class[] getParameterTypes()
      Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object.
    • Class getReturnType()
      Returns a Class object that represents the formal return type of the method represented by this Method object.
    • Object invoke(Object obj, Object... args)
      Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

For further information, you can have a look at java.lang.reflect.Method API.

  • Common methods of java.lang.reflect.Field

    Using Java Reflection API we can inspect the fields (member variables) of classes at runtime. This is achieved by using the java class java.lang.reflect.Field .

    • String getName()
      Returns the name of the field represented by this Field object.
    • Class getType()
      Returns a Class object that identifies the declared type for the field represented by this Field object.
    • Object get(Object obj)
      Returns the value of the field represented by this Field, on the specified object.

For further information, you can have a look at java.lang.reflect.Field API.

We may notice that all the above methods are referred to public member fields. In the example in the next section, we will also show a way for retrieving private member fields.

2. Java Reflection Example

Create a java class named RentCar.java with the following code:

RentCar.java

package com.javacodegeeks.core.reflection;

public class RentCar {

	private int rate;
	private String type;
	public int price;

	public RentCar(int length) {
		if (length < 455) {
			type = "small";
			rate = 35;
		} else if ((length >= 455) && (length < 495)) {
			type = "mid-sized";
			rate = 45;
		} else if (length >= 495) {
			type = "large";
			rate = 55;
		}
	}


	public int getRate() {
		return rate;
	}

	public String getType() {
		return type;
	}

	public void setRate(int rate) {
		this.rate = rate;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void computeRentalCost(int numDays) {
		price = numDays * rate;
		System.out
				.println("The cost of your rental car is " + price + " euros");
	}
}

This class will be called later at runtime.

Now, create another Java class named ReflectionExample.java with the following code:

ReflectionExample.java

package com.javacodegeeks.core.reflection;

import java.lang.reflect.*;
import java.util.Arrays;

public class ReflectionExample {
	public static void main(String[] args) {

		// Obtain the class object if we know the name of the class
		Class rental = RentCar.class;
		try {
			// get the absolute name of the class
			String rentalClassPackage = rental.getName();
			System.out.println("Class Name is: " + rentalClassPackage);

			// get the simple name of the class (without package info)
			String rentalClassNoPackage = rental.getSimpleName();
			System.out.println("Class Name without package is: "
					+ rentalClassNoPackage);

			// get the package name of the class
			Package rentalPackage = rental.getPackage();
			System.out.println("Package Name is: " + rentalPackage);

			// get all the constructors of the class
			Constructor[] constructors = rental.getConstructors();
			System.out.println("Constructors are: "
					+ Arrays.toString(constructors));

			// get constructor with specific argument
			Constructor constructor = rental.getConstructor(Integer.TYPE);

			// initializing an object of the RentCar class
			RentCar rent = (RentCar) constructor.newInstance(455);

			// get all methods of the class including declared methods of
			// superclasses
			// in that case, superclass of RentCar is the class java.lang.Object
			Method[] allmethods = rental.getMethods();
			System.out.println("Methods are: " + Arrays.toString(allmethods));
			for (Method method : allmethods) {
				System.out.println("method = " + method.getName());
			}

			// get all methods declared in the class
			// but excludes inherited methods.
			Method[] declaredMethods = rental.getDeclaredMethods();
			System.out.println("Declared Methods are: "
					+ Arrays.toString(declaredMethods));
			for (Method dmethod : declaredMethods) {
				System.out.println("method = " + dmethod.getName());
			}

			// get method with specific name and parameters
			Method oneMethod = rental.getMethod("computeRentalCost",
					new Class[] { Integer.TYPE });
			System.out.println("Method is: " + oneMethod);

			// call computeRentalCost method with parameter int
			oneMethod.invoke(rent, 4);

			// get all the parameters of computeRentalCost
			Class[] parameterTypes = oneMethod.getParameterTypes();
			System.out.println("Parameter types of computeRentalCost() are: "
					+ Arrays.toString(parameterTypes));

			// get the return type of computeRentalCost
			Class returnType = oneMethod.getReturnType();
			System.out.println("Return type is: " + returnType);

			// gets all the public member fields of the class RentCar
			Field[] fields = rental.getFields();

			System.out.println("Public Fields are: ");
			for (Field oneField : fields) {
				// get public field name
				Field field = rental.getField(oneField.getName());
				String fieldname = field.getName();
				System.out.println("Fieldname is: " + fieldname);

				// get public field type
				Object fieldType = field.getType();
				System.out.println("Type of field " + fieldname + " is: "
						+ fieldType);

				// get public field value
				Object value = field.get(rent);
				System.out.println("Value of field " + fieldname + " is: "
						+ value);

			}

			// How to access private member fields of the class

			// getDeclaredField() returns the private field
			Field privateField = RentCar.class.getDeclaredField("type");

			String name = privateField.getName();
			System.out.println("One private Fieldname is: " + name);
			// makes this private field instance accessible
			// for reflection use only, not normal code
			privateField.setAccessible(true);

			// get the value of this private field
			String fieldValue = (String) privateField.get(rent);
			System.out.println("fieldValue = " + fieldValue);

		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}

Let’s give a short explanation of the above code. Firstly, we obtain the class object of the class RentCar. Then, we use some methods from the class java.lang.Class so as to obtain the perspective information from the class RentCar. Afterwards, we retrieve the constructors of the class RentCar and we instantiate an object with the integer 455 as parameter. Also, we call two different methods for obtaining the methods provided by the class RentCar. The difference between the methods getMethods() and getDeclaredMethods() is that the first one retrieves all the methods provided by class RentCar including those methods inherited by the superclasses (in our case, this superclass is java.lang.Object), while the second one retrieves only the methods provided by our class.
Then, using the methods from the class java.lang.reflect.Method , we inspect informations of the computeRentalCost() method.
Afterwards, using the methods from the class java.lang.reflect.Field , we retrieve information of the public member fields of the class RentCar. In our case, only field int price is public.
Finally, we show a way to obtain information for private fields and for that purpose, we use the String type field which is private.

If we run the above code, we will have the following results:

  • Output:
Class Name is: com.javacodegeeks.core.reflection.RentCar
Class Name without package is: RentCar
Package Name is: package com.javacodegeeks.core.reflection
Constructors are: [public com.javacodegeeks.core.reflection.RentCar(int)]
Methods are: [public void com.javacodegeeks.core.reflection.RentCar.setType(java.lang.String), public void com.javacodegeeks.core.reflection.RentCar.computeRentalCost(int), public int com.javacodegeeks.core.reflection.RentCar.getRate(), public void com.javacodegeeks.core.reflection.RentCar.setRate(int), public java.lang.String com.javacodegeeks.core.reflection.RentCar.getType(), public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]
method = setType
method = computeRentalCost
method = getRate
method = setRate
method = getType
method = wait
method = wait
method = wait
method = equals
method = toString
method = hashCode
method = getClass
method = notify
method = notifyAll
Declared Methods are: [public void com.javacodegeeks.core.reflection.RentCar.setType(java.lang.String), public void com.javacodegeeks.core.reflection.RentCar.computeRentalCost(int), public int com.javacodegeeks.core.reflection.RentCar.getRate(), public void com.javacodegeeks.core.reflection.RentCar.setRate(int), public java.lang.String com.javacodegeeks.core.reflection.RentCar.getType()]
method = setType
method = computeRentalCost
method = getRate
method = setRate
method = getType
Method is: public void com.javacodegeeks.core.reflection.RentCar.computeRentalCost(int)
The cost of your rental car is 180 euros
Parameter types of computeRentalCost() are: [int]
Return type is: void
Public Fields are: 
Fieldname is: price
Type of field price is: int
Value of field price is: 180
One private Fieldname is: type
fieldValue = mid-sized

3. Download the source code

This was a Java Reflection example. Download the source code here: JavaReflectionExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz