Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java cast and call a string as method on an object

Tags:

java

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

like image 326
user373201 Avatar asked May 15 '26 01:05

user373201


1 Answers

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);
}
like image 175
Mohammad Banisaeid Avatar answered May 16 '26 13:05

Mohammad Banisaeid