In addition to the bean type name support described above, simplified support is provided
for bean subtypes.
Bean subtypes are similar in concept to bean type names, except for the following differences:
- You specify the list of possible subclasses through an annotation on a parent bean class.
- You do not need to register the subtype classes on the bean dictionary of the parser.
In the following example, the abstract class has two subclasses:
| // Abstract superclass
| @Bean(
| dictionary={A1.class, A2.class}
| )
| public abstract class A {
| public String f0 = "f0";
| }
|
| // Subclass 1
| @Bean(typeName="A1")
| public class A1 extends A {
| public String f1;
| }
|
| // Subclass 2
| @Bean(typeName="A2")
| public class A2 extends A {
| public String f2;
| }
When serialized, the subtype is serialized as a virtual "_type" property:
| A1 object = new A1();
| object.f1 = "f1";
| String json = Json5.of(object);
| assertEquals("{_type:'A1',f1:'f1',f0:'f0'}", json);
The following shows what happens when parsing back into the original object.
| A object = Json.to(json, A.class);
| assertTrue(object instanceof A1);