Carry forward annotation from interface to generated java class when using Immutables

喜欢而已 提交于 2019-12-07 12:30:22

问题


I am using Immutables (http://immutables.org) in my Java interface to generate builders and immutable object. I have created a custom method level annotation called @Primary (denoting which attribute is primary field) that I have used to annotate one of my methods in the Immutable interface. I don't see the annotation in the generated java class created by immutables. I tried looking at BYOA (Bring Your Own Annotation) but that does not help.

Is there a way to get the @Primary annotation onto the generated immutable java class?

UPDATE (Based on Sean's suggestion below)

I now have a below config based on

package-info.java

package com.mypackage;


import com.mercuria.recon.custom.annotation.Primary;
import org.immutables.value.Value;

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

@Target({ElementType.PACKAGE, ElementType.TYPE})
@Retention(RetentionPolicy.CLASS) // Make it class retention for incremental   compilation
@Value.Style(passAnnotations=Primary.class)
public @interface MyStyle {}

Primary Annotation

package com.mypackage.custom.annotation;

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Primary {

}

I am seeing an error in package-info.json where in it says MyStyle should be declared in its own file. I am not sure the above config is correct. Please can you advise where I am going wrong?


回答1:


You can configure which annotations to pass with the @Style annotation, which you can use on package level.

E.g. create a file called package-info.java in any package and annotate it with

@Style(passAnnotations=Primary.class)

See: Style customization (explains about where to store a @Style annotation, but doesn't mention the passAnnotations mechanism)

Here's an example package-info.java file:

@Style(passAnnotations = YourAnnotation.class)
package com.yourapp;

import com.yourapp.annotations.YourAnnotation;
import org.immutables.value.Value.Style;

note that the annotations are above the package declaration, and the imports below.



来源:https://stackoverflow.com/questions/42631472/carry-forward-annotation-from-interface-to-generated-java-class-when-using-immut

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!