你不能仅仅通过向混合类/接口添加属性来做到这一点,因为"Mix-in" annotations are a way to associate annotations with classes, without modifying (target) classes themselves, originally intended to help support 3rd party datatypes where user can not modify sources to add annotations.
你可以通过在你的混入界面中添加@JsonAppend来使用它,这个注解是用于在对象被序列化时向对象添加常规属性之外的虚拟属性。
它可以与混入功能一起使用,以避免修改原始 POJO。
让我们重写你的例子:
@JsonAppend(
props = {
@JsonAppend.Prop(
name = "timestamp", type = Long.class,
value = TimestampPropertyWriter.class
)
}
)
public interface TheirClassMixIn {}
为了完成这个故事,我将展示TimestampPropertyWriter 的实现。它只是一个知道如何在给定TheirClass 实例的情况下评估我们的“虚拟”属性值的类:
public class TimestampPropertyWriter extends VirtualBeanPropertyWriter {
public TimestampPropertyWriter() {
}
public TimestampPropertyWriter(BeanPropertyDefinition propDef,
Annotations contextAnnotations,
JavaType declaredType) {
super(propDef, contextAnnotations, declaredType);
}
@Override
protected Object value(Object bean,
JsonGenerator gen,
SerializerProvider prov) {
return System.currentTimeMillis();
}
@Override
public VirtualBeanPropertyWriter withConfig(MapperConfig<?> config,
AnnotatedClass declaringClass,
BeanPropertyDefinition propDef,
JavaType type) {
return new TimestampPropertyWriter(propDef, declaringClass.getAnnotations(), type);
}
}