【问题标题】:Returning Unknown Type Java返回未知类型 Java
【发布时间】: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


【解决方案1】:

多个返回类型通过相同的方法名

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

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

【讨论】:

  • 这正是我想要的!谢谢。在我要求编译的代码中,它确实可以编译。我有一个 return null; 来自我忘记包含在示例中的 try-catch。
猜你喜欢
  • 2014-03-19
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
相关资源
最近更新 更多