简体   繁体   中英

Convert a String representation of Object back to an Object of original type in java

I am using type conversion given below in my project.

**

ArrayList<Object> arr=new ArrayList<Object>();
String str=arr.toString();

**

I want to convert field str back into ArrayList<Object> type.

How to go through?

thanks for Help

您应该使用Serializable接口, ObjectOutputStream / ObjectInputStream和byte []进行字符串转换,例如DatatypeConverter.parseBase64Binary / DatatypeConverter.printBase64Binary

toString() is a protocol. It is defined to produce some string or another. It is not defined to produce a string reversible to an object. Many classes toString methods are designed to produce human readable results, which are nearly guaranteed to not be reversible.

The Java technology universe contains a number of mechanisms for serializing objects into bytes that can be stored or transmitted and then deserialized into objects. These include the built-in Java Object Streams, the build-in Java JAX-B XML marshal/unmarshaling technologies, and then open-source alternatives just as Jackson for mapping to and from Json or Yaml, and many others.

The only way to do this, is to Override the toString() method of the Object in your ArrayList. Say your object has 2 attributes: int size and String name . Your constructor would possible be

public YourObject(int size, String name){
    this.size = size;
    this.name = name;
}

Now you override your object:

@Override
public String toString(){
    return Integer.toString(this.size) + "#" + this.name;
}

In order to create the object again, you will also need another constructor or setter:

public YourObject(String attributes){
    String[] parts = attributes.split("#");
    this.size = Integer.parseInt(parts[0]);
    this.name = parts[1];
}

To go from object to string and back:

List<YourObject> arr; //Initialise this array
List<String> arrStrings = new ArrayList<String>();

//Convert to list of strings
for (YourObject yourObject : arr){
    arrStrings.add(yourObject.toString());
}

//Convert it back
List<YourObject> yourObjects = new ArrayList<YourObject>();
for (String converted : arrStrings){
    yourObjects.add(new YourObject(converted));
}

If you wish to use a native object, create your own object and extend the native.

Other than that, there is no way to do what you want. And note that this is very prone to error! So be sure to check for length of strings, sizes of arrays and whatnot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM