“自定义注记”中的“类型”作为参数的集合

时间:2017-08-10 09:56:28

标签: java annotations

我有一个自定义注释,如下所示:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
  String description();
  Class type;
}

我用它如下:

class MyClass {

  @CustomAnnotation(description="Some Description", type=MyClass.class)
  public void someMethod() {
  }
}

但是,我希望能够将MyClass列表指定为“类型”,如下所示:

class MyClass {

  @CustomAnnotation(description="Some Description", type=List<MyClass>.class)
  public void someMethod() {
  }
}

我觉得这是不可能的。我能做的是,在注释中添加另一个属性来指定类型是否为集合,但还有其他更好的选择吗?我相信没有,但要求以防万一有希望。

1 个答案:

答案 0 :(得分:0)

看到Rentention.RUNTIME我假设你想反思这个

List.classList<MyClass>.class在运行时引用相同的东西。

记住这一点:

  

泛型在运行时不存在。

在运行时,每个通用类型都是类型已删除,所以我怀疑你在这里尝试做什么可能是不可能的。您可以通过向注释添加另一个属性来解决此问题,但不知道您要对注释执行的操作,我并不完全确定。您可能希望使用反射从MyClass获取List<MyClass>.class。但是,让我告诉你,这是不可能的。

我的建议是使用List.class。在运行时,列表存储的对象类型并不重要。