1

Having my custom annotation:

@Inherited
@Target({ElementType.TYPE, ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityDomain {

}

My objective is declare an interface where the type parameter must be a type annotated with @EntityDomain

Such as:

@EntityDomain
public class Person implements Serializable {

I did a research in:

I have created

@FunctionalInterface
public interface EntityRetrievalForPersistence<@EntityDomain T> {

    T getEntity();

}

But something is missing because the following compiles:

public enum StringTest implements EntityRetrievalForPersistence<String>{

    A("A"),
    B("B");

    private String x;

    private StringTest(String x) {
        this.x = x;
    }

    @Override
    public String getEntity() {
        // TODO Auto-generated method stub
        return null;
    }

}

It should be marked how an error by the compiler because String is not annotated with @EntityDomain

What is the correct configuration?

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
  • 5
    there is no constraint for annotations, you will need to get that value using reflection and if necessary throw an exception at run time – ΦXocę 웃 Пepeúpa ツ Apr 04 '17 at 17:28
  • 1
    Alternatively, you can implement your own type checker that enforces such a custom constraint, i.e. define something like `interface EntityRetrievalForPersistence<@MustBeAnnotatedWith(EntityDomain.class) T> { … }`. On the other hand, *why*? What do you gain by that, or loose by the absence of it? How does it affect code dealing with instances of `EntityRetrievalForPersistence` whether the annotation on the type parameter is present or not? – Holger Apr 04 '17 at 17:36
  • Interesting. I thought it was a valid scenario. – Manuel Jordan Apr 04 '17 at 17:43
  • 2
    May i suggest another solution - why not just make `EntityDomain` a marker interface, and do: `public interface EntityRetrievalForPersistence` ? – paranoidAndroid Apr 04 '17 at 18:24
  • Good point, but according with the following http://stackoverflow.com/a/25850576/3665178 it for the point (3), seems better practice "How Annotations are better than Marker Interfaces?" – Manuel Jordan Apr 04 '17 at 19:32
  • 1
    Annotations can be more powerful than real Java types. However, if a regular Java type is enough to fit your needs, you should use it. See https://checkerframework.org/manual/#faq-typequals-vs-subtypes . – mernst Apr 05 '17 at 12:34
  • Thanks to all by the replies. Feel free to post an answer to approve it how valid and close this post. Thank you. – Manuel Jordan Apr 05 '17 at 13:02

0 Answers0