簡體   English   中英

獲取帶注釋的字段的名稱

[英]Get the name of an annotated field

如果我定義了這樣的注釋:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Input {

    String type() default "text";
    String name();
    String pattern() default "";

}

並將其用於以下方法:

@Column(name="nome", unique = true, nullable = false)
@Order(value=1)
@Input
private String nome;

@Column(name="resumo", length=140)
@Order(value=2)
@Input
private String resumo;

有什么方法可以將帶注釋的字段的名稱分配給屬性name (例如:對於String nome字段,該值將為nome ;對於String resumo字段,該值將為resumo )?

您不能將注釋變量默認為字段名稱。 但是,無論您在哪里處理注釋,都可以進行編碼,使其默認為字段名稱。 下面的例子

Field field = ... // get fields
Annotation annotation = field.getAnnotation(Input.class);

if(annotation instanceof Input){
    Input inputAnnotation = (Input) annotation;
    String name = inputAnnotation.name();
    if(name == null) { // if the name not defined, default it to field name
        name = field.getName();
    }
    System.out.println("name: " + name); //use the name
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM