获取带注释的字段的名称

Kle*_*ota 2 java reflection annotations

如果我定义了这样的注释:

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

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

}
Run Code Online (Sandbox Code Playgroud)

并将其用于以下方法:

@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;
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以将name带注释的字段的名称分配给属性(例如:对于该字段,String nome该值为nome,对于该字段String resumoresumo)?

Jp *_*ori 5

您不能将注释变量默认为字段名称。但是,无论您在哪里处理注释,都可以进行编码,使其默认为字段名称。下面的例子

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
}
Run Code Online (Sandbox Code Playgroud)