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();
user.setId(5);
//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++)
{
System.out.println(methods[i].getName());
if (methods[i].getName().equals(functionName))
return methods[i];
}
return null;
}
}


The code for sample class is as follows:

No comments:

Post a Comment

JSP - Java Description

https://docs.oracle.com/javaee/5/tutorial/doc/bnair.html Install Java on the computer:  https://phoenixnap.com/kb/install-java-windows Insta...