How to call a method of and object as a separate t

2019-06-11 13:24发布

I am trying to invoke a method in a class object via reflection. However, I want to run it as separate thread. Can someone tell me the changes I have to make on model.java or below code?

 thread = new Thread ((StatechartModel)model);
 Method method = model.getClass().getMethod("setVariable",newClass[]{char.class,t.getClass()});
 method.invoke(model,'t',t);

2条回答
Summer. ? 凉城
2楼-- · 2019-06-11 14:21

Let me suggest a simpler version once you have your target object available as a final:

final MyTarget finalTarget = target;

Thread t = new Thread(new Runnable() {
  public void run() {
    finalTarget.methodToRun(); // make sure you catch here all exceptions thrown by methodToRun(), if any
  }
});

t.start();
查看更多
趁早两清
3楼-- · 2019-06-11 14:28

You could do something like the following which just creates an anonymous Runnable class and starts it in a thread.

final Method method = model.getClass().getMethod(
    "setVariable", newClass[] { char.class, t.getClass() });
Thread thread = new Thread(new Runnable() {
    public void run() {
         try {
             // NOTE: model and t need to defined final outside of the thread
             method.invoke(model, 't', t);
         } catch (Exception e) {
             // log or print exception here
         }
    }
});
thread.start();
查看更多
登录 后发表回答