Search code examples
dependency-injectionannotationsconstructor-injectionhk2

HK2 Custom annotation Annotation disallowed on Constructor


Using HK2 injection framework i developed a custom annotation for injecting my custom object inside my classes.

All works fine if i annotate my objects as class variables:

public class MyClass {
    @MyCustomAnnotation
    MyType obj1

    @MyCustomAnnotation
    MyType obj2

     ...

Now i need to inject my objects as constructor parameters ie:

public class MyClass {

    MyType obj1        
    MyType obj2

    @MyCustomAnnotation
    public MyClass(MyType obj1, MyType obj2){
        this.obj1 = obj1;
        this.obj2 = obj2;
    }
     ...

In my injection resolver i overrided the:

@Override
public boolean isConstructorParameterIndicator() {
    return true;
}

in order to return true.

The problem is when i try to build my project it catches an error telling:

"The annotation MyCustomAnnotation is disallowed for this location"

What am i missing?


Solution

  • Sound like an annotation definition problem. The @Target on the annotation definition defines where the annotation is allowed. The allowed targets are in the ElementType enum set.

    ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE

    In order to able to target a constructor, you need to add CONSTRUCTOR to the @Target. You can have more than one target. For example

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

    See Also: