我想每隔一定时间更新对象属性(调用休息服务)。
我有对象定义和带有new和set的类
public class Obj {
private String data;
//Getters and setters
}
//A class with the new and sets:
Public class setData{
public setData{
Obj o = new Obj();
o.setdata("hello");
}
TimerTask timerTask = new MyTimerTask();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
}
public class MyTimerTask extends TimerTask {
@Override
public void run() {
/*
Here is the question. How can I update the data property of my object?
I need to call the rest service, and update. The data string is on a
swing UI.
*/
}
}
这是问题。如何更新对象的数据属性? 我需要致电其余服务,并进行更新。数据字符串在摆动UI上。
谢谢!
答案 0 :(得分:1)
为了从TimerTask
内部更新组件,您的任务必须具有对那些组件的引用。一种实现方法是在任务中添加一个构造函数,以使用要操作的对象对其进行初始化。
例如:
public class MyComponent {
private int data;
// getters / setters
}
public class MyTimerTask extends TimerTask {
private final MyComponent myComponent;
public MyTimerTask(MyComponent myComponent) {
super();
this.myComponent = myComponent;
}
@Override
public void run() {
// here you can access your component's data value
int val = this.myComponent.getData();
// do whatever you need to
}
}