user1145874
user1145874

Reputation: 969

Accessing static field in annotation

Im trying use a Java annotation in a Groovy class but have trouble to set a static field of a java class as a parameter:

The Annotation: Id.java

package x.y.annotations;

import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Id {

    public Class<Adapter> adapter();

    public Class<Object> targetType();

    public String targetAttribute();

    public String onDelete();

}

The java class with the static fields: XPerson.java

package x.y.static.domain;

public class XPerson {

    public static String ID;

}

And the groovy class, where the problem occurs: Person.groovy

package x.y.domain

import x.y.annotations.Id
import x.y.static.domain.XPerson

class Person {

    @Id(adapter = Adapter, targetType = XPerson, targetAttribute = XPerson.ID, onDelete = "delete")
    long id
}

Eclipse marks the "targetAttribute = XPerson.ID" part with:

Groovy:expected 'x.y.domain.XPerson.ID' to be an inline constant of type java.lang.String not a property expression in @x.y.annotations.Id

I also tried things like "XPerson.@ID" or defining a getter for the ID field, but nothing helped.

Any hints would be great.

Regards, michael

Upvotes: 3

Views: 5359

Answers (2)

G&#225;bor Lipt&#225;k
G&#225;bor Lipt&#225;k

Reputation: 9796

I have found a related issue in the Groovy JIRA. It is a bug. Should work. See https://issues.apache.org/jira/browse/GROOVY-3278

Upvotes: 5

Dave Newton
Dave Newton

Reputation: 160281

Annotation values may only be compile-time constant expressions. Making the field final is an option. (With the caveat that the field can't be initialized in a static initializer/etc. as the snippet implies.)

Upvotes: 3

Related Questions