Details
-
Type:
New Feature
-
Status:
Closed
-
Resolution: Fixed
-
Affects Version/s: None
-
Fix Version/s: 1.3
-
Component/s: None
-
Labels:None
Description
A huge number of PropertyEditors has been created and you could help the usage of these through adding a SingleValueConverter that utilizes a PropertyEditor. A Simple version that we've used is like this:
import java.beans.PropertyEditor;
import com.thoughtworks.xstream.converters.SingleValueConverter;
public class PropertyEditorValueConverter implements SingleValueConverter {
final private PropertyEditor editor;
final private Class type;
public PropertyEditorValueConverter(PropertyEditor editor, Class type) { this.editor = editor; this.type = type; }
public Object fromString(String str) { editor.setAsText(str); return editor.getValue(); }
public String toString(Object obj) { editor.setValue(obj); return editor.getAsText(); }
public boolean canConvert(Class type) {
return this.type.isAssignableFrom(type);
}
}
Here's a test case:
import java.awt.Color;
import junit.framework.TestCase;
import sun.beans.editors.ColorEditor;
public class PropertyEditorValueConverterTest extends TestCase {
PropertyEditorValueConverter converter = new PropertyEditorValueConverter(new ColorEditor(), Color.class);
public void testMatchesClass() throws Exception { assertTrue(converter.canConvert(Color.class)); assertFalse(converter.canConvert(Object.class)); }
public void testConverting() throws Exception { assertConvertWorks(Color.black); assertConvertWorks(Color.blue); assertConvertWorks(Color.yellow); }
private void assertConvertWorks(Color testObject) {
String string = converter.toString(testObject);
assertEquals(testObject, converter.fromString(string));
}
}
Just after commiting this I remembered that property editors are not thread safe.. I'll commit a thread safe version tomorrow (where the constructor argument is class for the property editor and the fromString / toString methods instantiate the class.