4

I have a Arraylist

List<?> myList=new ArrayList();

myList = fetchQuery(); //fetches the list of Entities

Now myList Has a list of Entities

Now i convert that list to string,so it is a string object now.

String temp=myList.toString();

My question is how to convert that temp string again to that myList(List of entities) ???

Any ideas??

My Temp Value looks like this

temp="[entityObject1,entityObject2.......]" ..

i could not extract each object and cast it with that entity class.. is there a way??

Thanks..

Kabilan S
  • 1,104
  • 4
  • 15
  • 31

4 Answers4

2

I have done a sample program to do this conversion. Things you have to be careful about. 1.The class whose list with which we will be working should have an over ridden toString method.(You can have your own toString() format but need to change the rest of implementation accordingly).

Sample content Object Class with over ridden toString() method.

class Sample {

    private String name;
    private String sex;

    @Override
    public String toString() {
        return "name=" + name + "&" + "sex=" + sex;
    }
    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @param sex
     *            the sex to set
     */
    public void setSex(String sex) {
        this.sex = sex;
    }

}

The Main Application.java

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class MainApplication {

    public static void main(String[] args) {
        List<Sample> e = new ArrayList<Sample>();
        Sample a1 = new Sample();
        a1.setName("foo1");
        a1.setSex("Male");

        Sample a2 = new Sample();
        a2.setName("foo2");
        a2.setSex("Male");
        e.add(a1);
        e.add(a2);

        String tmpString=e.toString();
        List<Sample> sampleList = (List<Sample>) chengeToObjectList(tmpString, Sample.class);
    }

    /**
     * Method to change String to List<Obj>.
     * @param listString
     * @param contentClass
     * @return List of Objects
     */
    public static Collection chengeToObjectList(String listString, Class contentClass) {

        Collection returnList = new ArrayList();

        // Code to remove [ and ] coming from the toString method
        if (listString.charAt(0) == '[') {
            listString = listString.substring(1);
        }
        if (listString.charAt(listString.length() - 1) == ']') {
            listString = listString.substring(0, listString.length() - 1);
        }

        String[] stringArray = listString.trim().split(",");
        for (int i = 0; i < stringArray.length; i++) {
            String[] contentArray = stringArray[i].trim().split("&");
            Object ob = null;
            try {
                ob = contentClass.newInstance();
            } catch (InstantiationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            for (int j = 0; j < contentArray.length; j++) {

                String[] keyValueArray = contentArray[j].trim().split("=");

                String fieldName = keyValueArray[0].trim();
                //Code to make the 1st char uppercase
                String s = String.valueOf(fieldName.toCharArray()[0]);
                s = s.toUpperCase();
                fieldName = s + fieldName.substring(1);

                String fieldValue = keyValueArray[1].trim();

                Class[] paramTypes = new Class[1];
                paramTypes[0] = String.class;
                String methodName = "set" + fieldName; 
                Method m = null;
                try {
                    m = contentClass.getMethod(methodName, paramTypes);
                } catch (NoSuchMethodException m) {
                    m.printStackTrace();
                }
                try {
                    String result = (String) m.invoke(ob, fieldValue);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e1) {
                    e1.printStackTrace();
                }
            }
            returnList.add(ob);
        }

        return returnList;
    }
}
Akhi
  • 2,242
  • 18
  • 24
0

It depends on toString() implementation if you have exposed each field in toString() in particular format parsing it reverse you can get the original object formatted, but generally this is not the case

For example:

You can't form person instance from string because id is not exposed

class Person{
  private long id;
  private String name;
  //stuffs
  @Override
  public String toString(){ return "Person  :" +name;}
}

See Also

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • toString() is a default method right..I am using hibernate so it returns a list of Entities(means a list of a particular class with all columns)..i couldnt reconvert that string object again to that original list – Kabilan S Jun 13 '12 at 12:51
  • you could override `toString()`, but why do you need this ? – jmj Jun 13 '12 at 12:53
  • see my fetchQuery method() will return a list of the below class.. class Person{ private long id; private String name; } – Kabilan S Jun 13 '12 at 12:56
  • Why would you do this conversion ? – jmj Jun 13 '12 at 13:02
  • I need this because i have a generic method(myList fetched), and it returns only string ..Many methods are dependant on this..I need that myList in another new method im writing and i want to use that generic method only .. – Kabilan S Jun 13 '12 at 14:11
0

When you do myList.toString(); you actually call the AbstractCollection.toString() method, which in turn calls the toString() method of each of the objects in the List.

Unless the toString() method of the Entity class serializes the objects in such a way that you can reconstruct them afterwards, you can't do anything.

If it does serialize them properly, you would need to parse the temp String, identify all the individual strings for each Entity object and reconstruct them from there.

This can only be done if the serialized strings for each of the Entity objects do not contain the square brackets and comma characters, or if they escape them properly. This is because the AbstractCollection.toString() method uses these special characters when building your temp String.

If all the above conditions are met, you can use regular expressions to parse the temp string and obtain each of the individual serialized Entity objects. Then it's up to you to reconstruct the objects and add them to a new List.

For regular expressions in Java, see http://docs.oracle.com/javase/6/docs/api/java/util/regex/package-summary.html .

Marius Ion
  • 387
  • 3
  • 10
  • Could clarify why you believe that brackets or commas would be a problem to parse the string back into a set of Objects? – Edwin Dalorzo Jun 13 '12 at 13:05
  • when i do that String temp=myList.toString(); ..the string value is like this ---->temp="[entityObject1,entityObject2.......]" .. i couldn extract each object and cast it with that entity class.. is there a way?? – Kabilan S Jun 13 '12 at 14:04
0

Here's an idea:

Make the toString method of your Entity class generate an XML string compatible with some kind of serializer like JAXB or XStream. Then, when you get a Collection.toString(), split it by Entity (perhaps String.split() could help). Long story short, you want the entity XML definition back in a String that you can pass to you XML deserializer which, in turn, can convert you strin back into an Object of that type.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205