得到注释值?

jon*_*ney 6 java reflection annotations

如何在注释中设置值?

我定义了以下注释:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonElement {
    int type();
}
Run Code Online (Sandbox Code Playgroud)

以下是在POJO类中使用它的方法

@JsonElement(type=GETTER_METHOD)
public String getUsername{
........................
}
Run Code Online (Sandbox Code Playgroud)

而util类使用反射来检查此方法是否存在JSonElement注释,并检查类型值是什么.

Method methods[] = classObject.getClass().getDeclaredMethods();

        JSONObject jsonObject = new JSONObject();
        try {
            for (int i = 0; i < methods.length; i++) {
                String key = methods[i].getName();
                System.out.println(key);
                if (methods[i].isAnnotationPresent(JsonElement.class) && key.startsWith(GET_CHAR_SEQUENCE)) {
                    methods[i].getDeclaredAnnotations();
                    key = key.replaceFirst(GET_CHAR_SEQUENCE, "");
                    jsonObject.put(key, methods[i].invoke(classObject));
                }

            }
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
Run Code Online (Sandbox Code Playgroud)

我如何找出type()价值是多少?我可以找到是否存在注释,但我找不到一个方法来找出设置的值 - 如果有的话type().

Pet*_*ček 16

JsonElement jsonElem = methods[i].getAnnotation(JsonElement.class);
int itsTypeIs = jsonElem.type();
Run Code Online (Sandbox Code Playgroud)

请注意,您必须确保jsonElem不是null由您的

isAnnotationPresent(JsonElement.class)
Run Code Online (Sandbox Code Playgroud)

或者简单

if (jsonElem != null) {
}
Run Code Online (Sandbox Code Playgroud)

校验.


此外,如果您将注释更改为

public @interface JsonElement {
    int type() default -1;
}
Run Code Online (Sandbox Code Playgroud)

您不必在代码type中的每个出现时都声明属性@JsonElement- 它将默认为-1.

您还可以考虑使用enumfor而不是一些整数标志,例如:

public enum JsonType {
    GETTER, SETTER, OTHER;
}

public @interface JsonElement {
    JsonType type() default JsonType.OTHER;
}
Run Code Online (Sandbox Code Playgroud)