Link to home
Start Free TrialLog in
Avatar of boise2004
boise2004

asked on

does function knows who called it? if so can function use that information to re-call?

Is it possible, in Java, from function1 to call function2, and have function2 identify function1?
(in other words, function2 know who called it)

Is it possilbe to have function2 then call function1 on another object -- otherObject.function1()?

If so, how?

Thank you.

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you can determine the *class* that called it, but not the object instance
> Then function2 could call function1 on another object by reflection


reflection is *not* needed, you can call the method directly
>> You could pass function1 as (String) parameter to function2.
Assuming function1 is not the same all the time.
I mean it can be doThis() as well as doThat() and doSomethingElse()
>> Assuming function1 is not the same all the time.
Then reflection *is* needed. Depends on your needs, boise.
To give you an idea:

public void function2(String methodToCall) {      // parameter is the method to call

      // .....

      Object anotherObject = ....;

      Method method=null;
      try {
           method = anotherObject.getClass().getMethod(methodToCall, new Class [] {});  // check if the method (without parameters) exists on this class
           if (method!=null) { // if it does...
           try {
                 method.invoke(anotherObject, null);  // ... invoke it
           } catch (Exception e) {
               // .........
           }
      } catch (NoSuchMethodException e) {
            // ......
      }

}
theres no need to pass the method name around, you can just use:

anotherObject.function1()

anotherObject would of course need to be of a class that contains a function1() method

let me know if you have any questions :)
>> theres no need to pass the method name around
True *IF* the method to call is *always* function1().

My solution assumes the above is *not* the case.
I clearly said that in my comment:
>> Assuming function1 is not the same all the time.
you wouldn't pass the function name as a string, you would instead pass the Method directly

public void function2(Object otherObject, Method callingMethod) throws Exception {
   callingMethod.invoke(otherObject, null);
}


careful you don't get stuck in an endless loop though :)

you can probably get rid of the need for doing it at all though.

for example you could use a callback interface and have the object that needs calling implement that interface

public void function2(Callback cb) {
   cb.callBack();
}

let me know if u have any questions?