Interview Questions

Java - Reflection

Reflection is used to examine the run time behavior of Java applications running in the Java Virtual machine.

Using reflection, instances can be created using the fully qualified names of the class.

Note: Reflection is a more powerful and advanced feature. It should not be used extensively unless the developer has a strong knowledge in Java.

In the below example, let us see how to create an object for the class and invoke its methods at run time using reflection.

Example:
Consider the following class Student. This class has a hash map (temporary database) which has Student Roll number and Student Name as key value pairs. It has two methods, 1. getStudentName and 2. getNumberOfStudents. Now, Let us see how to invoke these methods at run time using Reflection.

Student Class

package in.techdive.reflection.demo;

import java.util.HashMap;

public class Student
{
        private static HashMap<String, String>  database        = new HashMap<String, String>();

        static
        {
                database.put("1001", "Jack");
                database.put("1002", "Jill");
        }

        public String getStudentName(String rollNumber)
        {
                return database.get(rollNumber);
        }

        public int getNumberOfStudents()
        {
                return database.size();
        }
}

Reflection Usage

 /**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.reflection.demo;

import java.lang.reflect.Method;

class Reflection
{
        public static void main(String[] args)
        {
                try
                {
                        // Load the Class "Student"
                        Class c = Class.forName("in.techdive.reflection.demo.Student");

                        // Create an instance for class Student
                        Object obj = c.newInstance();

                        /*
                         * Now lets try to invoke the "getNumberOfStudents" method which is having no input parameters. This method
                         * return integer as response
                         */

                        Method mtd1 = c.getMethod("getNumberOfStudents", null);
                        Object responseCount = mtd1.invoke(obj, null);
                        System.out.println("Number of Students = " + responseCount);

                        /*
                         * Now lets try to invoke the method "getStudentName" which has input parameter as String. This method
                         * returns the Student name as String.
                         */

                        Class parameterType[] = new Class[1];
                        parameterType[0] = String.class; // Since roll number is String in our case

                        Object parameterValue[] = new Object[1];
                        parameterValue[0] = "1001"; // Lets pass the roll number as String

                        Method mtd2 = c.getMethod("getStudentName", parameterType);
                        Object responseName = mtd2.invoke(obj, parameterValue);
                        System.out.println("Student Name = " + responseName);
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                }
        }
}

Output:

Number of Students = 2
Student Name = Jack