有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组Java:通过注释检查列表中是否存在属性值

作为标题,我想通过注释检查列表中是否存在属性值。例:

private final String[] list = {"a", "b", "c", "d"}
@Includes(list = list)
private String state;

但是有一个错误Attribute must be constant 我怎么做?顺便问一下,通过注释检查这是一个好的解决方案吗? 这是我的注解:

@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Includes {
    String[] list();
}

共 (1) 个答案

  1. # 1 楼答案

    错误清楚地表明:

    The value for annotation attribute Includes.list must be an array initializer

    对于非数组变量,值必须是final和static,但是,对于数组,无法做到这一点。这意味着您必须进行以下变通:

    @Includes(list = {"a", "b", "c", "d"})
    private String state;
    

    此外,数组初始化错误,请使用{}而不是[]