我正在编写一个库,旨在供其他应用程序使用,包含一堆实现相同接口的类,如以下示例所示:
public interface Figure {
// ...
}
public class Triangle implements Figure {
// ...
}
public class Square implements Figure {
// ...
}
public class Circle implements Figure {
// ...
}
然后我为上面的所有类创建了一个mixin:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(Triangle.class),
@JsonSubTypes.Type(Square.class),
@JsonSubTypes.Type(Circle.class)
})
public interface FigureMixin {
}
我可以像往常一样将这个mixin添加到ObjectMapper
中:
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Figure.class, FigureMixin.class);
问题是库的用户可能希望提供他们自己的实现Figure
的类。因此,注解方法并不合适,因为我不知道在编译时有多少JSON子类型(即实现Figure
的类)。
有没有办法在运行时为所有实现公共接口的可用类注册子类型,即实现相同的mixin配置,但不使用注解?
先谢了。
1条答案
按热度按时间ou6hu8tu1#
受the example here的启发,我能够实现所需的行为:
首先,在所有类实现的接口中使用
@JsonTypeInfo
:然后,将我的所有类作为子类型注册到ObjectMapper中:
当然,如果需要的话,对
registerSubtypes(...)
的调用可以放在不同的方法中。