java.io.file 无法转换为自定义类

标签 java inheritance

我的代码:

FileChooser prompt = new FileChooser();
prompt.setTitle("Odaberi fajl");
source = (Source) prompt.showOpenDialog(new Stage());

其中 source 是一个扩展 File 的类:

    import java.io.File;

public class Source extends File {

    public Source(String pathname) {
        super(pathname);
    }
}

尝试转换到源时返回错误。我不知道是什么原因造成的。

最佳答案

FileChooser 返回一个File。是什么让您认为可以将其转换为 Source?它不是

您想要做的是以下之一:

  1. 使Source封装一个File并提供您需要的任何自定义方法,并根据需要委托(delegate)给所包含的File

    public class Source {
        private File f;
        public Source(File f) {
            this.f = f;
        }
        // Custom methods
        ...
        // Delegating methods
        public boolean exists() {
            return f.exists();
        }
        ...
    }
    
  2. 像您正在做的那样扩展File,但提供一个构造函数,该构造函数接受另一个File(即复制构造函数)并实例化Source 使用传递的 File 中的数据。

    public class Source extends File {
        public Source(File f) {
            super(f.getAbsolutePath());
        }
        // Custom methods
        ...
    }
    

然后实例化如下:

FileChooser prompt = new FileChooser();
prompt.setTitle("Odaberi fajl");
source = new Source(prompt.showOpenDialog(new Stage()));

关于java.io.file 无法转换为自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414846/

相关文章:

java - Mac 上的 java 安装 (xerces) 问题

java - 在java中读取 double 可以是线程安全的吗?

java - threadpoolexecutor 中 worker 和 workQueue 的用途

Django模板继承: how many levels and what page to render

Javascript继承问题

C++ : restrict access to the superclass' methods selectively?

java - 创建自定义分页指示器

java - 可交换工作队列

c++ - 为什么我必须通过this指针访问模板基类成员?

Java 枚举继承 : Is it possible to somehow extract the enums' toString() method to a common super class/enum?