【问题标题】:How can I get multiple annotations defined by a user, that have the types of parameters expected in a constructor?如何获得用户定义的多个注释,这些注释具有构造函数中预期的参数类型?
【发布时间】:2013-11-25 02:40:59
【问题描述】:

假设我有一个 Course() 构造函数,其参数如下:String name 和 int age。

我希望用户使用注解,指定构造函数或方法具有的参数。

类似这样的:

@Param (param = String.class)
@Param (param = int.class)
public Course(String name, int age) {
    super();
    this.name = name;
    this.age = age;
}

这样以后,当我得到构造函数时,我可以从注释中推断出我必须使用哪些参数来获取该类的实例。

package DomainModel;

public @interface Param {
    Class<?> param();
    //ArrayList<Class<?>> params;
}

非常感谢所有帮助,谢谢!

【问题讨论】:

  • 请注意,反射已经为您提供了参数类型。
  • 天哪... 是吗?我现在要调查一下。顺便说一句,我忘了提。我不知道它是什么类类型!!它可能是任何东西。
  • 查看Method 和Constructor 类。
  • 知道了!谢谢=)

标签: java reflection annotations


【解决方案1】:

像这样定义你的注释...

 public @interface Param {
          String name();
          Integer age();
 }

那么你的用户可以这样使用..

@Param (name="your_name", age=your_age)
public void setCourse(String name, int age) {


}

那么您需要反思以将您的注释值分配给您的成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多