Lab 21: Reflections

Reflections are a way to explore the structure of a program. They are very useful when you need to make your code very flexible. Here are two files: The Employee.java file creates a record of an employee. Suppose the record is kept at a central site. The EmployeeQuery.java is the program used to query the contents of an employee record. For this example, there is only one record. Suppose the EmployeeQuery.java file is used at remote sites.

Now suppose you need to make a change to the Employee.java file. That would require you to also make changes to the EmployeeQuery.java file and send those updates to all the remove sites. Instead, you can use reflections to let the EmployeeQuery.java file handle any changes made to Employee automatically.

To use reflections, you need to import java.lang.reflect.*.

Reflections are used to examine the contents of a class. For example, if you have an object that is a String s = new String(), you can use the statement Class cls = s.getClass();, and now cls is a variable that stores the contents of s.

To get a method from s, you can use

Method method = cls.getMethod(methodName, parameterArray);
The second parameter is a list of parameter types for the method you want. To get a method with no parameters, just pass in an empty array: new Class[0].

Method stores a method. To call the method, use
method.invoke(s, argumentArray)
s is the object you are calling the method on, and argumentArray is an array of arguments to pass to the method. If you are calling a method with no arguments, pass an empty array: new Object[0].

For the lab, change the code so that you call whatever method the user types in and you print the result of calling that method.