JAVA不兼容的类型:无法将对象转换为我的类型

mac*_*ey7 6 java javafx

我试图通过在单独的线程上进行工作并返回所需的对象来对JavaFX中的GUI进行更改。但是,在完成工作和task.setOnSucceeded()之后,我尝试检索创建的对象并得到错误“不兼容的类型:对象无法转换为VideoScrollPane类型”。

我认为这与原始类型有关,因为它发生在侦听器中,但是四处查看后找不到我想要的建议。

任何可以散发出的光将不胜感激。

Task task = new Task<VideoScrollPane>() {
    VideoScrollPane vsp;
    @Override protected VideoScrollPane call() {
        try {
            System.out.print("thread...");

            ExecutorService executor = Executors.newCachedThreadPool();
            Future<VideoScrollPane> future = executor.submit(new Callable<VideoScrollPane>() {
                @Override public VideoScrollPane call() {
                    return new VideoScrollPane(mediaview, vboxCentre, username, project);
                }
            });

            vsp = future.get();
        } catch(Exception exception) { System.out.println(exception.getMessage()); }

        return vsp;
    }
};
new Thread(task).start();

task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
    @Override public void handle(WorkerStateEvent t) {
        System.out.println("complete");

        try {

            //where the problem occurs
            VideoScrollPane v = task.get();     

        } catch(Exception exception) { System.out.println(exception.getMessage()); }
    }
});
Run Code Online (Sandbox Code Playgroud)

Min*_*esh 5

这是因为task.get()正在返回一个类型的值Object,但您试图将它分配给 v,这是一个VideoScrollPane。您可以通过执行强制转换来防止错误,就像这样

VideoScrollPane v = (VideoScrollPane)task.get();
Run Code Online (Sandbox Code Playgroud)

请注意,如果task.get()返回不是 a 的内容VideoScrollPane,您将得到一个ClassCastException.

但是,如果您想完全避免该问题,请考虑task通过包含泛型参数的类型来修复 , 的声明。你可以把它改成,

Task<VideoScrollPane> task = new Task<VideoScrollPane>() {
Run Code Online (Sandbox Code Playgroud)

这样,task.get()现在将返回 a VideoScollPane,您将不需要演员表。

  • 更正任务的声明比使用不必要的向下转换要好。这样可以确保返回的实际对象是正确的类型。 (3认同)