ilmoeuro / snakeyaml

Automatically exported from code.google.com/p/snakeyaml
0 stars 0 forks source link

Interface for constructing immutable objects #15

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I thought you might find this interesting/useful. 

I recently created a class that lets you create a "blueprint" for an
object, which includes a way to deserialise objects via a single call to a
constructor.

http://github.com/freenet/plugin-Library-staging/blob/master/src/plugins/Library
/io/ObjectBlueprint.java

At the moment, I'm using it as an adapter between my code and SnakeYAML:

static ObjectBlueprint<MyClass> my_blueprint;
static {
    try {
        my_blueprint = new ObjectBlueprint<MyClass>(MyClass.class,
Arrays.asList("field1", "field2", "field3"));
    } catch (NoSuchFieldException e) {
        throw new AssertionError(e);
    } catch (NoSuchMethodException e) {
        throw new AssertionError(e);
    }
}

In a Represent:

public Node representData(Object data) {
    return representMapping("!MyClass",
my_blueprint.objectAsMap((MyClass)data), true);
}

In a Construct:

public Object construct(Node node) {
    MyClass my_object;
    try {
        my_object =
my_blueprint.objectFromMap((Map)constructMapping((MappingNode)node));
    } catch (Exception e) {
        //java.lang.InstantiationException
        //java.lang.IllegalArgumentException
        //java.lang.reflect.InvocationTargetException
        throw new ConstructorException(/* etc */);
    }
    return my_object;
}

This technically works, but I'm guessing is inefficient, because it uses
that intermediate map.

Maybe you could extend this blueprint class and integrate it into
SnakeYAML, so that this process can happen more directly? It would then
give a nice interface to define how to construct/represent immutable objects.

Original issue reported on code.google.com by infinity0x@gmail.com on 22 Aug 2009 at 5:07

GoogleCodeExporter commented 9 years ago
I studied the code but I must say I do not understand how it can be integrated.
Construction of immutable objects is already implemented in version 1.4.
There is no clear and easy solution for dumping immutable objects yet. 
Currently it 
is dumped as map instead of sequence.
I am investigating how to solve it (preferably it must be some sort of setting, 
one 
should not extend or overwrite code). You are welcome to propose any solution.

Original comment by py4fun@gmail.com on 3 Sep 2009 at 6:53

GoogleCodeExporter commented 9 years ago
ok, sure. i understand my suggestion was very vague. i'll look into this some 
more
when i get some time. :)

Original comment by infinity0x@gmail.com on 4 Sep 2009 at 11:49

GoogleCodeExporter commented 9 years ago

Original comment by py4fun@gmail.com on 4 Sep 2009 at 5:14