简体   繁体   English

可空注释未出现在字段中

[英]Nullable Annotation not appears in field

I'm using Java Reflections for get model's fields and some fields are Nullables with the @Nullable annotation. 我正在使用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
}

And when I try to get the annotations of fields, any field has annotations :( I don't know why. 当我尝试获取字段的注释时,任何字段都具有注释:(我不知道为什么。

Can you help me please. 你能帮我吗。

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(",")) + ");";
}

Nullable annotation is not retained for reflective access. 不保留可为空的注释以进行反射访问。 I cannot use it for this. 我不能为此使用它。 I need write my own annotation with Retained annotation for use and get it whit java refelctions. 我需要使用保留的注释编写自己的注释以供使用,并将其添加到Java refelctions中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM