Tuesday, February 16, 2010

Simple Reflection Example

I am working on extracting various pieces of information from different classes of objects. I thought that rather than manually going through and using getters for the fields of each object, I would try using reflection. The code below is a simple use of reflection. I create a Class object of the type of class for the object, then I get the method of that class. Finally, the method of the object is invoked to get the required information out.

package utils;

import java.lang.reflect.Method;

public class ClassSpy
public static void main(String[] args) throws Exception
//Specify the class that we will do a reflection on
String className = "utils.SampleClass";
//Create a Class object associated with className
Class toRun = Class.forName(className);
//create an instance of the method which we
will later invoke
Method method = findMethod(toRun, "getId");
//create an instance of the class
SampleClass user = new SampleClass();
//invoke the method
int id = (Integer)method.invoke(user);
System.out.println("id "+id);
private static Method findMethod(Class clazz,
String functionName) throws Exception
Method[] methods = clazz.getMethods();
for (int i=0; i<methods.length; i++)
if (methods[i].getName().equals(functionName))
return methods[i];
return null;

The code for sample class is as follows:

No comments:

Post a Comment

VBA Excel to Double Click change to checkmark or x

 Note that to do this, you need to set the font of the affected cells to Winding 2 first: 1 2 3 4 5 6 7 8 9 10 11 12 Private Sub Worksheet...