I have some data that looks like this
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
And I'm wondering what the best way to create a bunch of objects from it would be. I've written the following regex to extract all the values from a particular Key...
Pattern p_keyone = Pattern.compile("keyone:\"(.+?)\"\\,");
Matcher match_keyone = p_keyone.matcher(string);
while(match_keyone.find()) {
开发者_高级运维 myobjects.add(new MyObject(match_keyone.group(1));
}
Which gives me a bunch of objects with a single argument...
myobjects.add(<valueone>);
Is there a way I can execute a single regex query and create a bunch of objects with all the values as arguments in one go. Like this...
new MyObject( <valueone>, <valuetwo> , <valuethree> );
Thanks
Your approach is not bad.
Few things you could change, though it depends on your requirements whether they make sense:
- Create a "Factory" class which takes 1 line of data and creates the object.
- Read the data line by line, for each line use the Factory to create it.
- Depending on how fancy (and error-prone) you want it to get, you could even read the names of the objects and properties and then use reflection to create instances and set the properties.
String.split()
could help:
String line = "myobject{keyone:\"valueone\",keytwo:\"valuetwo\",keythree:\"valuethree\"}"
// ^-----[0]------^ ^--[1]-^ ^--[2]-^ ^--[3]-^ ^--[4]---^ ^--[5]---^ ^[6]
String[] parts = line.split("\"");
MyObject myObject = new MyObject(parts[1], parts[3], parts[5]);
精彩评论