I am trying to create some classes serializable by Jackson. I want to annotate some elements with standard Jackson annotation (let's consider JsonIgnore for this example) but I want them to have effect only in my specific mapper.
So I decided to create my own annotations like standard ones (e. g. MyJsonIgnore) and process them only in an annotation introspector used by my mapper. I've found overridable method _findAnnotation. Javadoc says the following:
...overridable that sub-classes may, if they choose to,
mangle actual access block access ("hide" annotations)
or perhaps change it.
I've found a way to block some annotations (however it involves overriding _hasAnnotation, not _findAnnotation) but I am completely stuck with changing annotations.
Here is some minimal example of what I am trying to do:
object Mappers {
/**
* Same as JsonIgnore but mapper-specific
*/
annotation class MyJsonIgnore(val value: Boolean = true)
private class MyIntrospector : JacksonAnnotationIntrospector() {
override fun <A : Annotation> _findAnnotation(
annotated: Annotated,
annoClass: Class<A>
): A {
if (annoClass == JsonIgnore::class.java && _hasAnnotation(annotated, MyJsonIgnore::class.java)) {
val mji = _findAnnotation(annotated, MyJsonIgnore::class.java)
return JsonIgnore(mji.value) // Does not compile, type mismatch
// return JsonIgnore(mji.value) as A // Does not compile, annotation class cannot be instantiated, same as Java, see below
}
return super._findAnnotation(annotated, annoClass)
}
}
fun myMapper(): ObjectMapper {
return ObjectMapper().setAnnotationIntrospector(MyIntrospector())
}
}
I also cannot do it with Java:
public class Mappers {
/**
* Same as JsonIgnore but mapper-specific
*/
public @interface MyJsonIgnore {
boolean value() default true;
}
private static class MyIntrospector extends JacksonAnnotationIntrospector {
@Override
protected <A extends Annotation> A _findAnnotation(Annotated annotated,
Class<A> annoClass) {
if (annoClass == JsonIgnore.class && _hasAnnotation(annotated, MyJsonIgnore.class)) {
MyJsonIgnore mji = _findAnnotation(annotated, MyJsonIgnore.class);
return new JsonIgnore(mji.value()); // Does not compile, JsonIgnore is abstract
}
return super._findAnnotation(annotated, annoClass);
}
}
static ObjectMapper myMapper() {
return new ObjectMapper().setAnnotationIntrospector(new MyIntrospector())
}
}
So what is the supposed way to change annotations by overriding this method? Is there any? Is my approach right or should I do it other way?