【发布时间】:2015-07-06 06:33:10
【问题描述】:
所以我在 Java 中使用 JSON,而 JSON 可以有一个数组或一个对象的基础。在我的 Config 类中,我将类作为参数,因此如果文件不存在,我可以相应地创建文件。我还将该类存储为私有字段,以便将来知道。
但是,当我开始读取文件时,我希望通过相同的方法名称具有多个返回类型。如果我返回Object,那么我必须转换我想要避免的返回值。
当前代码:
public class Config {
private File dir = null;
private File file = null;
private Class clazz = null;
public Config(String program, String fileName, Class root) throws IOException {
this.dir = new File(System.getProperty("user.home") + File.separator + program);
if (!this.dir.exists()) {
this.dir.mkdir();
}
this.file = new File(this.dir + File.separator + fileName);
if (!this.file.exists()) {
this.file.createNewFile();
if (root.getName().equals(JSONArray.class.getName())) {
Files.write(this.file.toPath(), "[]".getBytes());
} else if (root.getName().equals(JSONObject.class.getName())) {
Files.write(this.file.toPath(), "{}".getBytes());
}
}
this.clazz = root;
}
public JSONArray readConfig() {
return null;
}
public JSONObject readConfig() {
return null;
}
}
有没有我可以做我想做的事而不必返回Object?
【问题讨论】:
-
标准答案是为您打算读取的不同类型的数据简单地使用不同的方法(即
readConfigArray()、readConfigObject())。 -
@dimo414 我知道这样做是一个标准,但是我的问题是,有可能做我想做的事吗?
-
你试过编译吗?
-
@t3dodson 我还在修改,所以不,还没有。
-
在返回之前强制转换声明为对象的返回值仍然会返回一个对象;调用者将收到与没有强制转换相同的对象。重要的是声明的类型。
标签: java json methods overloading