我的代码:
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
?它不是源
。
您想要做的是以下之一:
使
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(); } ... }
像您正在做的那样扩展
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/