> I'm using the Preferences class and have some objects to represent with
> Strings for storage.
[quoted text clipped - 3 lines]
> Now saving a property is not a problem I just have a CustomProperty
> interface and call toPropertyString().
So far, so good.
> But loading a property is a case of documenting that CustomProperty
> classes must provide a no arg public contstructor, and then I can call
> CustomProperty.fromPropertyString(myPropStr) to populate the object.
As you already noticed below the interface method
public void fromPropertyString(String)
breaks immutability.
> Now I'd really like to have immutable properties, and I realise I can have
> a toImmutableInstance() method but are there any better solutions to my
> goal?
I would modify your requirement (interface CustomProperty) as follows:
(*) The class has to provide a public constructor taking a String argument.
(*) The class does *not* have to provide a fromPropertyString(String)
method. (hence you don't have to give up immutability)
Obviously the loading from a string gets more clumsy then.
But at least one can tuck away that clumsiness into a utility method:
public static Object createFromPropertyString(String s) {
try {
Constructor ctor = c.getDeclaredConstructor(new Class[]{String.class};
return ctor.newInstance(new Object[]{s});
} catch(Exception e) {
throw new RuntimeException(e);
}
}

Signature
Thomas
Thomas Fritsch - 03 May 2007 15:29 GMT
[...]
> public static Object createFromPropertyString(String s) {
Oops, I meant
public static Object createFromPropertyString(Class c, String s) {
> try {
> Constructor ctor = c.getDeclaredConstructor(new Class[
{String.class});
> return ctor.newInstance(new Object[]{s});
> } catch(Exception e) {
> throw new RuntimeException(e);
> }
> }
Usage example:
MyRectangle rect =
(MyRectangle) createFromPropertyString(MyRectangle.class, "0,0,50,100");

Signature
Thomas
visionset - 03 May 2007 17:39 GMT
> I would modify your requirement (interface CustomProperty) as follows:
> (*) The class has to provide a public constructor taking a String
[quoted text clipped - 13 lines]
> }
> }
Thanks, that makes more sense.
I can also Generify it which I really wanted to do.
static <T> CompoundProperty
createFromPropertyString(String propStr, Class<T> clazz) {
try {
Constructor ctor = clazz.getDeclaredConstructor(
new Class[]{String.class});
Object instance = ctor.newInstance(new Object[]{propStr});
return (CompoundProperty)instance;
} catch(Exception ex) {
throw new RuntimeException(ex);
}
}