Nullable Annotation不会出现在字段

时间:2017-12-19 01:54:56

标签: java android reflection

我正在使用Java Reflections获取模型的字段,而某些字段是带有@Nullable注释的Nullables。

public class Category implements Serializable {

    private String id;
    private String name;
    @Nullable
    private String description;
    @Nullable
    private String urlIcon;
    private ArrayList<String> sounds;

    //Getters and setters
}

当我尝试获取字段的注释时,任何字段都有注释:( 我不知道为什么。

你能帮帮我吗?

public static <T> String getCreateSentence(Class<T> clazz) {
    StringBuilder sentence = new StringBuilder("CREATE TABLE " + clazz.getSimpleName() + " (");
    //Loop for ever field in Model
    for (Field field : clazz.getDeclaredFields()) {
        if (field.getType().isPrimitive() && !field.getName().equals("serialVersionUID")) {
            if (field.getType().equals(Integer.TYPE)
                    || field.getType().equals(Boolean.TYPE)
                    || field.getType().equals(Byte.TYPE)
                    || field.getType().equals(Long.TYPE)
                    || field.getType().equals(Short.TYPE)) {
                //field.isAnnotation is false ever and field.getDeclaredAnnotations has 0 items ever
                if (field.isAnnotationPresent(Nullable.class)) {
                    sentence.append(field.getName()).append(" INT NULL, ");
                } else {
                    sentence.append(field.getName()).append(" INT NOT NULL, ");
                }
            } else {
                //I evaluate another field types
            }
        }
    }

    return sentence.substring(0, sentence.lastIndexOf(",")) + ");";
}

1 个答案:

答案 0 :(得分:0)

不保留可为空的注释用于反射访问。我不能用它。我需要使用保留注释编写我自己的注释以供使用,并获得它的java反射。

像这样:http://www.java2s.com/Tutorials/Java/java.lang.reflect/Field/Java_Field_getAnnotation_Class_lt_T_gt_annotationClass_.htm