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