java string 转对象,将String转换为类对象

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

How to do that? Please help me with source code.

解决方案

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.

If you did this:

SomeClass object = ...

String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and

code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.

If you did something like this:

SomeClass object = ...

Class c = object.getClass();

String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)

If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

The Java Object Serialization APIs as described in the links in @Nishant's answer.

JSON serialization as described in @fatnjazzy's answer.

An XML serialization library like XStream.

An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:游动-白 设计师:我叫白小胖 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值