简体   繁体   English

Java自定义注释不可见

[英]Java custom annotation not visible

For my project I am converting classes to json with jackson fasterXml. 对于我的项目,我正在使用jackson fastXml将类转换为json。 Now I have to change in one place the way the objects are converted so that @JsonIgnore is ignored and the property is serialised. 现在,我必须在一个地方更改对象转换的方式,以便忽略@JsonIgnore并序列化属性。

I found out that I can do this with extending a JacksonAnnotationIntrospector and a custom annotation. 我发现可以通过扩展JacksonAnnotationIntrospector和自定义注释来做到这一点。 The problem is that the custom annotation is only visible if it is defined in the same package/project/osgi bundle as the implementing class while I would like to define it in the service package which exposes the json convertion. 问题在于,只有在与实现类在同一包/项目/ osgi包中定义了自定义批注的情况下,该自定义批注才可见,而我想在公开json转换的服务包中对其进行定义。 If the annotation is in the implementing package, I cannot reference it in the JacksonAnnotationIntrospector and I would need to check on the name of the annotation. 如果注释在实现包中,则无法在JacksonAnnotationIntrospector中引用它,我需要检查注释的名称。

I have two identical annotations with only difference the package: 我有两个完全相同的注释,只是包装不同:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationName {

}

When I set both on the implementation, I only see the annotation defined from within the same package/project/osgi bundle as the implementation class. 当在实现上同时设置两者时,我只能看到与实现类在同一包/项目/ osgi包中定义的注释。 Is there a constraint regarding this or has anyone an idea what could be the problem? 是否对此有限制,或者有人知道可能是什么问题?

Put your custom annotation in a unique package ideally using a reverse domain name you control. 理想情况下,最好使用您控制的反向域名将自定义注释放入唯一的程序包中。 Put this into a separate API bundle (at least for now). 将其放入一个单独的API捆绑包中(至少现在是这样)。

In your user code add the API bundle to the maven dependencies and use the new annotation. 在用户代码中,将API捆绑包添加到maven依赖项,并使用新的注释。 The maven-bundle-plugin (or what you use) should create an Import-Package statement in your Manifest. maven-bundle-plugin(或您使用的工具)应在清单中创建一个Import-Package语句。 This will make sure the annotation can be wired at runtime. 这将确保注释可以在运行时进行连接。

In the code where you parse the annotations make sure you use the classloader of the user bundle. 在解析批注的代码中,确保使用用户捆绑包的类加载器。 This classloader should be able to see the standard annotations as well as the custom one. 这个类加载器应该能够看到标准注释和自定义注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM