简体   繁体   中英

Create a new Shape from the value of String.valueOf(Object obj)

I'm trying to figure out the most efficient way to create a new Shape instance from given String , which is eg a value returned by String.valueOf(Object obj) static method for the Shape parameter. Let's say I created a Circle and I've added few additional features to it:

Circle circle = new Circle(10, 10, 10, Color.BLACK);
circle.setStroke(Color.RED);
circle.setStrokeWidth(2);

Now, I'm writing the value returned by String.valueOf(circle) , which is:

Circle[centerX=10.0, centerY=10.0, radius=10.0, 
fill=0x000000ff, stroke=0xff0000ff, strokeWidth=2.0]

...in a *.txt file, or something similar to that. Next, I read this *.txt file and I put it's content in a new String , say:

String stringCircle = "Circle[centerX=10.0, centerY=10.0, radius=10.0, "
                + "fill=0x000000ff, stroke=0xff0000ff, strokeWidth=2.0]";

What would be the best approach to create a new Circle instance from stringCircle value?

Consider overriding the toString method of Circle to return an easily readable string of values, and then writing the constructor, public Circle(String definition) to read that String accordingly.

The string could be something like 10.0 10.0 10.0 0x000000ff 0xff0000ff 2.0 Since you've implemented the toString and the constructor, you can assume the parameter order is always the same and then use a string tokenizer with a space as the delimiter to easily assign the values.

You can grab each value just by parsing the stringCircle string, something like this:

int newStart = stringCircle.indexOf(",");
double centerX = Double.parseDouble(stringCircle.substring(stringCircle.indexOf("=") + 1, newStart));
stringCircle = stringCircle.substring(newStart + 1);

newStart = stringCircle.indexOf(",");
double centerY = Double.parseDouble(stringCircle.substring(stringCircle.indexOf("=") + 1, newStart));
stringCircle = stringCircle.substring(newStart + 1);
//...
newStart = stringCircle.indexOf(",");
int stroke = Integer.parseInt(stringCircle.substring(stringCircle.indexOf("=") + 1, newStart));
stringCircle = stringCircle.substring(newStart + 1);
//...

and then pass them as you need, to constructors and suchlike. This could be done in a loop as well, if you put the parsed results into an array for example.

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