返回未知类型的 Java [英] Returning Unknown Type Java

查看:54
本文介绍了返回未知类型的 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

然而,当我开始阅读文件时,我更喜欢有多个返回类型,尽管方法名称相同.如果我返回 Object,那么我必须转换我想避免的返回值.

当前代码:

公共类配置{私有文件目录 = null;私人文件文件=空;私有类 clazz = null;public Config(String program, String fileName, Class root) 抛出 IOException {this.dir = new File(System.getProperty("user.home") + File.separator + program);如果 (!this.dir.exists()) {this.dir.mkdir();}this.file = new File(this.dir + File.separator + fileName);如果 (!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 = 根;}公共 JSONArray 读取配置(){返回空;}公共 JSONObject 读取配置(){返回空;}}

无论如何我可以做我想做的事而不必返回Object?

解决方案

同一个方法名的多个返回类型

好吧,可以使用通用函数来实现这一点.例如,

public static void main(String[] args) {尝试 {String t = getObject(String.class);整数 d = getObject(Integer.class);} 捕获(异常 e){e.printStackTrace();}}公共静态<T>T getObject(Class returnType) 抛出异常 {if(returnType == String.class) {返回(T)测试";} else if(returnType == Integer.class) {返回(T)新整数(0);} 别的 {返回 (T) returnType.newInstance();}}

<块引用>

下面的代码会编译吗?

恐怕不行.很少有编译错误如

public Object readConfig() {尝试 {//假设 jsonString 存在返回 (this.clazz.getDeclaredConstructor(String.class).newInstance(jsonString));<--- clazz 应该是 getClass()} catch (InstantiationException | IllegalAccessException|IllegalArgumentException |调用目标异常|NoSuchMethodException |安全异常 e) {e.printStackTrace();<---- 缺少 return 语句}}

So I'm working with JSON in Java and JSON can have a base of either an Array or an Object. In my Config class, I take a class as an argument so I can create the file accordingly if it doesn't exist. I also store the class as a private field so I know in future.

However, when I get to reading the file, I'd prefer to have multiple return types though the same method name. If I return Object, I then have to cast the returned value which I want to avoid.

Current code:

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

}

Is there anyway I can do what I want without having to return Object?

解决方案

multiple return types though the same method name

well, it is possible to use generic function to achieve that. For example,

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?

I'm afraid no. There are few compilation errors such as

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆