繁体   English   中英

返回未知类型的Java

[英]Returning Unknown Type Java

因此,我正在使用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就可以做我想做的事情?

具有相同方法名称的多个返回类型

很好,可以使用通用函数来实现。 例如,

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

以下代码还会编译吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM