This is a little Java trick that came out of the following Problem Statement: How to call a pre-defined method of an invoking class if it is defined in it? Or, invocation through precedence.
If I have three classes Invoker1, Invoker2 and MyUtility and both Invokers call a method of MyUtility, Is it possible for MyUtility to call a method of the Invoker if defined instead of it's own? I call it a transfer of power pattern - An Invoker class dictates what to call not by condition or heirarchy but by definition of its location.
// -- MyUtility.javaThe way this application works is if preInvocation method is defined in an invoking class, MyUtility should call it instead of it's own. A workflow is defined in a way that does not require a tight integration with an Object hierarchy.
public class MyUtility {
private void preInvocation () {
...
}
public void doSomething () {
System.out.println ("I am doing something");
}
}
// -- Invoker1.java
public class Invoker1 {
public void invoke () {
new MyUtility ().doSomething ();
}
public void preInvocation () {
System.out.println ("Invoker1's preInvocation called");
}
}
// -- Invoker2.java
public class Invoker2 {
public void invoke () {
new MyUtility ().doSomething ();
}
}
How to do it? Define MyUtility in the following way:
Have fun!
// -- MyUtility.java
public class MyUtility {
private void preInvocation() {
System.out.println("Pre-Invocation of MyUtility");
}
public void doSomething() {
Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();
String callerClassName = elements[1].getClassName();
Class clz;
try {
clz = Class.forName(callerClassName);
Method method =
clz.getDeclaredMethod("preInvocation", null);
method.invoke(clz.newInstance(), new Object[] { });
} catch (Exception exp) {
// -- Any Exception and call it's own.
preInvocation();
}
}
}
# Run Invoker1 => Invoker1's preInvocation called
# Run Invoker2 => Pre-Invocation of MyUtility
No comments:
Post a Comment