gpt4 book ai didi

java - 返回未知类型 Java

转载 作者:行者123 更新时间:2023-12-01 22:15:05 25 4
gpt4 key购买 nike

所以我正在 Java 中使用 JSON,并且 JSON 可以具有数组或对象的基础。在我的 Config 类中,我将一个类作为参数,这样如果文件不存在,我可以相应地创建该文件。我还将该类存储为私有(private)字段,以便将来知道。

但是,当我开始读取文件时,我希望通过相同的方法名称拥有多个返回类型。如果我返回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

最佳答案

multiple return types though the same method name

嗯,可以使用通用函数来实现这一点。例如,

public static void main(String[] args) {
try {
String t = getObject(String.class);
Integer d = getObject(Integer.class);
} catch (Exception e) {
e.printStackTrace();
}
}

public static <T> T getObject(Class<T> returnType) throws Exception {
if(returnType == String.class) {
return (T) "test";
} else if(returnType == Integer.class) {
return (T) new Integer(0);
} else {
return (T) returnType.newInstance();
}
}

Will the following code even compile?

恐怕不行。很少有编译错误,例如

public Object readConfig() {
try {
// Assume jsonString exists
return (this.clazz.getDeclaredConstructor(String.class).newInstance(jsonString)); <--- clazz should be getClass()
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
e.printStackTrace();
<---- missing return statement
}
}

关于java - 返回未知类型 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31239060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com