Reputation: 5578
in a method, I need to call some code but after the method's return call. How do I do this?
// this call needs to happen after the return true call
xmlRpcClient.invoke("newDevices", listDeviceDesc);
return true;
Upvotes: 1
Views: 815
Reputation: 36977
IMO, doing something "after the return was called" but before the calling method has processed the return value is indistinguishable from doing it before the return, so you should ask yourself, when exactly you want it to happen.
In a Swing GUI Application, you can use SwingUtilities.invokeLater
to delay the execution of a runnable until "everything else" is done. This is sometimes useful when a single user action causes a lot of listeners to be executed (one component loses focus, another components gets it, and said other component is also activated... all with a single mouse click).
Upvotes: 0
Reputation: 5903
Like JohnHopkins said use try{return true;}finally{yourCode}
to execute to code after the return was called. But IMHO this isn't properly thought through and I would change the design of the program. Can you tell us a bit more about your thought behind this to understand your way?
What you probably want to do:
public void myMethod() {
return true;
}
if(myMethod()) {
client.invoke()
}
Upvotes: 5
Reputation: 421
You could use an anonymous Thread to achieve what you want and add an one second delay inside.
try{return true;}finally{yourCode}
will not do the trick, since finally will be executed before the method actually returns.
new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// this call needs to happen after the return true call
xmlRpcClient.invoke("newDevices", listDeviceDesc);
}
}.start();
return true;
Upvotes: 1
Reputation: 3842
I was reading up on the finally
block in Java, and I learned that it will always be executed, unless the JVM crashes or System.exit()
is called. Some more information can be found in this StackOverflow question. Given this information, this should work for you.
try {
return true;
} catch (Exception e) {
// do something here to deal with anything
// that somehow goes wrong just returning true
} finally {
xmlRpcClient.invoke("newDevices", listDeviceDesc);
}
Upvotes: 0