我正在使用此类执行一些后台任务

class Download extends Task{
     protected Object call() throws Exception {
        try {
            updateMessage("Establishing Connection");
            DownloadHelper downloadHelper = new DownloadHelper();
            downloadHelper.performTask();
            return null;
        } catch (IOException | ParseException ex) {
            logger.error(ExceptionUtils.getStackTrace(ex));
            throw ex;
        }
    }
}


该任务依次调用DownloadHelper来执行某些任务。

class DownloadHelper{
    public DownloadHelper(){
    }

    public void performTask(){
    ----
    ----
    }
}


有没有办法从DownloadHelper类更新任务API的状态消息(updateMessage())?

最佳答案

权宜之计是将对Download任务的引用作为参数传递给DownloadHelper构造函数。为了最大程度地减少耦合,您可以将对updateMessage()的实现的引用传递为类型为Consumer的参数,即“接受单个输入参数且不返回结果的操作”。

DownloadHelper helper = new DownloadHelper(this::updateMessage);


然后,您的助手的performTask()实现可以根据需要要求updateraccept()消息。

Consumer<String> updater;

public DownloadHelper(Consumer<String> updater) {
    this.updater = updater;
}

public void performTask() {
    updater.accept("Helper message");
}


相关示例可见here

javafx - 从JavaFX中的Task API调用的嵌套函数更新标签-LMLPHP

import java.util.function.Consumer;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * @see https://stackoverflow.com/q/45708923/230513
 */
public class MessageTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("MessageTest");
        StackPane root = new StackPane();
        Label label = new Label();
        root.getChildren().add(label);
        Scene scene = new Scene(root, 320, 120);
        primaryStage.setScene(scene);
        primaryStage.show();
        Download task = new Download();
        task.messageProperty().addListener((Observable o) -> {
            label.setText(task.getMessage());
        });
        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();
    }

    private static class Download extends Task<String> {

        @Override
        protected String call() throws Exception {
            updateMessage("Establishing connection");
            DownloadHelper helper = new DownloadHelper(this::updateMessage);
            helper.performTask();
            return "MessageTest";
        }

        @Override
        protected void updateMessage(String message) {
            super.updateMessage(message);
        }
    }

    private static class DownloadHelper {

        Consumer<String> updater;

        public DownloadHelper(Consumer<String> updater) {
            this.updater = updater;
        }

        public void performTask() {
            updater.accept("Helper message");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}

07-27 21:43