返回未知类型 Java

Returning Unknown Type Java

所以我在 Java 中使用 JSON 并且 JSON 可以有数组或对象的基础。在我的配置 class 中,我将 class 作为参数,因此如果文件不存在,我可以相应地创建该文件。我还将 class 存储为私有字段,以便将来知道。

但是,当我开始阅读文件时,我更希望有多个 return 类型,尽管方法名称相同。如果我 return Object,那么我必须转换我想避免的 returned 值。

当前代码:

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;
    }

}

有没有什么办法可以让我做我想做的事而不必 return 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
    }
}