确定对象类型然后从 Snake yaml.load(InputStream) 转换对象的方法

发布于 2024-10-06 04:17:32 字数 491 浏览 0 评论 0原文

因此,我正在为所有要继承的模型对象编写这个实用程序类,以便每当我调用 saveToFile(filename) 时,它都会以 yaml 格式保存该对象。 To String 仅以 yaml 格式输出文件。我真正想要做的是使用文件中的属性初始化对象的所有属性,但我不想事先知道它是什么类型的对象。

我想要一个与此类似的方法

public void loadFromFile(String filename){
    try {
        InputStream input = new FileInputStream(new File(filename));
        Yaml y = new Yaml();
        this = y.load(input);
    } catch (IOException e) {
        System.out.println(e);
    }
}

可以正常工作,除了您无法将对象分配给“this”这一事实之外。

So I'm writing this utility class for all my model objects to inherit from so that whenever I call saveToFile(filename) it will save that object in a yaml format. To String just outputs the file in yaml format. What I really want to be able to do though is initialize all the attributes of an object with the attributes in a file but I don't want to have to know what type of object it is beforehand.

I want a method something along the lines of

public void loadFromFile(String filename){
    try {
        InputStream input = new FileInputStream(new File(filename));
        Yaml y = new Yaml();
        this = y.load(input);
    } catch (IOException e) {
        System.out.println(e);
    }
}

this works fine, save for the fact that you can't assign an object to "this".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌路黄昏 2024-10-13 04:17:32

您必须进行转换:

YourObject object = (YourObject) y.load(input);

另外,不要对 this 进行赋值。相反,您应该从外部加载对象并使用类似 BeanUtils.copyProperties(object, yamlObject) 的内容。

另请参阅 yamlbeans.

顺便说一句,为了创建一个实用方法,你的演员表不会那样工作。您最好将 Class 参数传递给该方法,并让它具有返回类型 T。使用 clazz.cast(..) 进行转换。

You will have to cast:

YourObject object = (YourObject) y.load(input);

Also, don't do assignments to this. Instead you should load the object externally and use something like BeanUtils.copyProperties(object, yamlObject)

Also take a look at the yamlbeans.

Btw, in order to make a utility method, your cast won't work like that. You'd better pass a Class<T> argument to the method, and let it have return type T. The use clazz.cast(..) to do the cast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文