pascallouisperez / jsonmarshaller

JsonMarshaller is a Java 1.5 library that allows marshalling and unmarshalling of JSON objects to and from entities ("Java classes").
Apache License 2.0
1 stars 0 forks source link

Allow marshalling anonymous subclasses of polymorphic @Entity subclasses #45

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
It's sometimes nice, in tests, to initialize an @Entity instance using an 
instance initializer. This works for simple @Entity types, but fails for 
polymorphic ones.

For example, this works:

  @Entity
  static class Foo {
    @Value Integer bar;
  }

  TwoLattes.createMarshaller(Foo.class).marshall(new Foo() {{
    bar = 3;
  }});

...but this doesn't work:

  @Entity(discriminatorName = "type", subclasses = Foo2.class)
  static class Foo {
    @Value Integer bar;
  }

  @Entity(discriminator = "foo2")
  static class Foo2 extends Foo {
    @Value Integer baz;
  }

  TwoLattes.createMarshaller(Foo.class).marshall(new Foo2() {{
    bar = 3;
    baz = 4;
  }});

It produces this error:

java.lang.IllegalArgumentException: Unmarshalled entity of class class 
com.SampleTest$1is not a valid subclass entity of class com.SampleTest$Foo
    at com.twolattes.json.PolymorphicEntityDescriptor.marshall(PolymorphicEntityDescriptor.java:106)
    at com.twolattes.json.PolymorphicEntityDescriptor.marshall(PolymorphicEntityDescriptor.java:12)
    at com.twolattes.json.EntityMarshallerImpl.marshall(EntityMarshallerImpl.java:42)
    at com.twolattes.json.EntityMarshallerImpl.marshall(EntityMarshallerImpl.java:38)
    at com.twolattes.json.EntityMarshallerImpl.marshall(EntityMarshallerImpl.java:17)

When implementing, just need to ensure that the anonymous type declares no 
@Value fields or methods and that its immediate superclass is an @Entity class 
that has a discriminator.

Original issue reported on code.google.com by jaredjac...@gmail.com on 2 Nov 2012 at 7:05

GoogleCodeExporter commented 9 years ago
What you are suggesting would require run-time reflection for unknown cases. 
I'm fine if we special case those and keep the rest fast.

Original comment by pas...@squareup.com on 2 Nov 2012 at 12:14

GoogleCodeExporter commented 9 years ago
Agreed. It's definitely not worth a measurable performance hit to the common 
case.

Original comment by jaredjac...@gmail.com on 2 Nov 2012 at 4:16