3

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

Roman C
  • 49,761
  • 33
  • 66
  • 176
user373201
  • 10,945
  • 34
  • 112
  • 168
  • 2
    http://docs.oracle.com/javase/tutorial/reflect/ – JB Nizet Aug 21 '13 at 12:45
  • if you are going to use reflection I'd suggest using Apache's reflection utilities. There are lots of useful methods in there and it's much less boilerplate donkey work. – Link19 Aug 21 '13 at 12:54

3 Answers3

1

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);
}
Mohammad Banisaeid
  • 2,376
  • 27
  • 35
0

The possible ways to solve this in Java is to write code that covers all cases with lots of if and else and instanceof expressions.

You will need to implement something like ObjectConverter as in this answer,

Or you can always use Java Reflection API.

Community
  • 1
  • 1
Waqas Memon
  • 1,247
  • 9
  • 22
  • 1
    You're saying there is only one way of doing this and then you giving another option ? – Marc-Andre Aug 21 '13 at 12:50
  • 1
    No problem I just find it weird and wanted to let you know. Sorry if it sounds aggressive or something that was not my intention. – Marc-Andre Aug 21 '13 at 12:52
0

My go-to solution for things like this is a handy library called jOOR - for 'Java Object Oriented Reflection'. It's a fluent wrapper around Java's reflection tools, which lets you write code like so:

String firstName = on(target).call("getFirstName").get();

With the above, ANY object 'target' with a method called getFirstName will work here, and the get() will (try to) cast the result as a string. Pretty handy if you know you only have to deal with a specific set of types that are guaranteed to have the methods you're interested in, but don't want to write and maintain an enormous if-else block.

David
  • 2,602
  • 1
  • 18
  • 32