Java 用一个自定义注释替换复杂的注释组合
在我当前的项目中,我有一组大而复杂的注释,我必须在我的课堂上的许多字段上添加注释。它们是json注释Java 用一个自定义注释替换复杂的注释组合,java,annotations,Java,Annotations,在我当前的项目中,我有一组大而复杂的注释,我必须在我的课堂上的许多字段上添加注释。它们是json注释 @JsonSerialize(using = IViewableToReferenceSerializer.class, contentUsing = IViewableToReferenceSerializer.class) private ComplexeObject myObject; 我想用这样的东西来代替它: @JsonAsReference private ComplexeObj
@JsonSerialize(using = IViewableToReferenceSerializer.class, contentUsing = IViewableToReferenceSerializer.class)
private ComplexeObject myObject;
我想用这样的东西来代替它:
@JsonAsReference
private ComplexeObject myObject;
我已经在没有自定义注释的情况下对系统进行了测试,它运行良好。我想我可以将注释定义为(例如):
所以我的问题是:这有可能吗?还是我只是做错了什么
更新:我在这篇文章中找到了杰克逊案件的答案
但是我愿意接受任何通用的案例解决方案。使用默认的jackson库,您将不会有任何运气 这里是来自JacksonAnnotationInterspector的代码片段(来自jackson 1.9.13)
在此线程中找到Jackson json的答案。。。但是我想知道一个大概的答案。谢谢你,雷内,但是就像我说的关于杰克逊的特殊案例一样,我已经找到了一个解决方案。。。这比你的简单多了。好的。因此,如果您不能使用其他库,我的回答只是一个提示。:)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JsonSerialize(using = IViewableToReferenceSerializer.class, contentUsing = IViewableToReferenceSerializer.class)
public @interface JsonAsReference {
}
public Object findSerializer(Annotated a)
{
/* 21-May-2009, tatu: Slight change; primary annotation is now
* @JsonSerialize; @JsonUseSerializer is deprecated
*/
JsonSerialize ann = a.getAnnotation(JsonSerialize.class);
if (ann != null) {
Class<? extends JsonSerializer<?>> serClass = ann.using();
if (serClass != JsonSerializer.None.class) {
return serClass;
}
}
....
}
AnnotationIntrospector annIntr = ....; // your implementation
ClassIntrospector<? extends BeanDescription> intr = new BasicClassIntrospector();
VisibilityChecker<?> vc = VisibilityChecker.Std.defaultInstance();
TypeFactory typeFactory= TypeFactory.defaultInstance();
SerializationConfig serConfig = new SerializationConfig(intr, annIntr, vc, null,
null, typeFactory, null);
DeserializationConfig deserConfig = new DeserializationConfig(intr, annIntr, vc, null,
null, typeFactory, null);
// null means use a default implementation
ObjectMapper objectMapper = new ObjectMapper(null, null, null, serConfig, deserConfig);