Reputation: 1
Right now, I'm working on a project, and my setup is something like this: I have a class (Foo
) which has several methods inside of it which must be activated at different times by the main class.
I've been researching this for quite a while, and the only thing I can find is the Timer
class, which doesn't quite work, as it can seemingly only time a class, and I don't want 25 different classes for such a basic program.
How do I activate each method in Foo
individually?
Upvotes: 0
Views: 224
Reputation: 2509
The following class works using an extension of TimerTask
(MethodTimerTask
) which take in input the Foo
instance and the method name to call.
In this way, using reflection, the different methods can be called at different times with only one extended TimerTask
class.
public class MyTimerTaskExample {
/**
* @param args
*/
public static void main(String[] args) {
Timer timer = new Timer();
Foo foo = new Foo();
timer.schedule(new MethodTimerTask(foo, "method1"), 1000);
timer.schedule(new MethodTimerTask(foo, "method2"), 3000);
}
public static class MethodTimerTask extends TimerTask {
private String methodName;
private Foo fooInstance;
private Exception exception;
public MethodTimerTask(Foo fooInstance, String methodName) {
this.methodName = methodName;
this.fooInstance = fooInstance;
}
@Override
public void run() {
try {
Foo.class.getMethod(methodName).invoke(fooInstance);
} catch (Exception e) {
this.exception = e;
}
}
public Exception getException() {
return exception;
}
public boolean hasException() {
return this.exception != null;
}
}
public static class Foo {
public void method1() {
System.out.println("method1 executed");
}
public void method2() {
System.out.println("method2 executed");
}
}
}
Bonus: the method getException()
returns the eventual Exception catched while executing methodName
of Foo
.
Upvotes: 1