dnault dnault - 6 months ago 48
JSON Question

Jackson: programmatically determine subtypes

Given an arbitrary

Class
object, what is the best way to determine the subtypes of that class registered with Jackson?

For example, here's a simple case where classes
Lion
and
Penguin
are subtypes of
Animal
:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(Lion.class),
@JsonSubTypes.Type(Penguin.class)})
public static abstract class Animal {}

@JsonTypeName("Lion")
public static class Lion extends Animal {}

@JsonTypeName("Penguin")
public static class Penguin extends Animal {}


My dream function would look like:

List<Class> getSubTypeClasses(Class c) {...}


where
getSubTypeClasses(Animal.class)
would return
Lion
and
Penguin
.

If the Jackson API doesn't provide a convenient way to get this information I will read the annotations manually, but it would be nice to know of a technique compatible with any
AnnotationIntrospector
implementation.

Answer

There is currently no mechanism for doing that. But you could file a request for adding something like this: given a base class, return a set of known sub-types along with type ids used for them, and the default implementation use. This seems like a reasonable thing to provide access for.

In the meantime (new feature could be available for 2.3, so it'd take some time), have a look at AnnotationIntrospector and see what methdods are available there, and how jackson-databind uses it to build mapping information. You should not have to write all of that manually, even without accessor.