I am using AOP to find the value of an instance variable before its going to be set and after it is set. So I am intercepting all setxxx methods and trying to do a getxxx before and after.
//actual instance
Object target = joinPoint.getTarget();
//Type of the instance
Class objectClass = target.getClass();
I want to call a string "getFirstName()" that is actually a method name on the actual instance (target). How can I do so
right now I can do the following
if (target instanceof User) {
instanceVarCurrentValue = ((User) target).getFirstName();
}
But i cannot check for instance of for all objects in my project and for each class I will have to check all properties
You need to use Reflection. You must find the method on class and invoke it.
Please see the below code:
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
User user = new User();
String name = runMethod(user, "getFirstName");
System.out.println(name);
}
private static String runMethod(Object instance, String methodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = instance.getClass().getMethod(methodName);
return (String)method.invoke(instance);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With