2

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?

Alex
  • 1,515
  • 2
  • 22
  • 44
  • Sounds like an annotation definition problem. Make sure you have the [`ElementType.CONSTRUCTOR`](https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html) in the `@Target`. Did you not have a compiler error (in your IDE) before trying to build? – Paul Samsotha Nov 12 '15 at 09:10
  • oh...yes.. you're right... can i specify just one target? what if i want the annotation to work both with variable AND constructor? – Alex Nov 12 '15 at 09:16
  • `@Target({.. , ... , ... })` :-) – Paul Samsotha Nov 12 '15 at 09:16
  • 1
    great! it works... really helpful as always!!! thanks – Alex Nov 12 '15 at 09:34

1 Answers1

1

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:

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720