Search code examples
javaimmutables-library

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


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?


Solution

  • 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.