2

使用 HK2 注入框架,我开发了一个自定义注释,用于在我的类中注入我的自定义对象。

如果我将我的对象注释为类变量,一切正常:

public class MyClass {
    @MyCustomAnnotation
    MyType obj1

    @MyCustomAnnotation
    MyType obj2

     ...

现在我需要将我的对象作为构造函数参数注入,即:

public class MyClass {

    MyType obj1        
    MyType obj2

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

在我的注入解析器中,我覆盖了:

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

为了返回真。

问题是当我尝试构建我的项目时,它会捕获一个错误消息:

"The annotation MyCustomAnnotation is disallowed for this location"

我错过了什么?

4

1 回答 1

1

听起来像一个注释定义问题。@Target注释定义上的 定义允许注释的位置。允许的目标在ElementType枚举集中。

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

为了能够以构造函数为目标,您需要添加CONSTRUCTOR@Target. 你可以有多个目标。例如

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

也可以看看:

于 2015-11-12T09:42:06.370 回答