确定对象类型然后从 Snake yaml.load(InputStream) 转换对象的方法
因此,我正在为所有要继承的模型对象编写这个实用程序类,以便每当我调用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须进行转换:
另外,不要对
this
进行赋值。相反,您应该从外部加载对象并使用类似BeanUtils.copyProperties(object, yamlObject)
的内容。另请参阅 yamlbeans.
顺便说一句,为了创建一个实用方法,你的演员表不会那样工作。您最好将
Class
参数传递给该方法,并让它具有返回类型T
。使用 clazz.cast(..) 进行转换。You will have to cast:
Also, don't do assignments to
this
. Instead you should load the object externally and use something likeBeanUtils.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 typeT
. The useclazz.cast(..)
to do the cast.