简体   繁体   English

检查注解类型@transient

[英]check for annotation type @transient

I want to skip fields annotadet with @transient in a query builder.我想在查询构建器中跳过带有@transient 的字段注释。

Something like就像是

if(!fcol.annotationType().equals(@Transient){ do something }

somebody have any idea?有人知道吗?

Reflections reflections = new Reflections(packageName);
reflections.getFieldsAnnotatedWith(javax.persistence.Transient.class))

You can check whether the field has the annotation using the following method on the field (assuming your fcol is of type java.lang.reflect.Field):您可以在字段上使用以下方法检查该字段是否具有注释(假设您的 fcol 是 java.lang.reflect.Field 类型):

   /**
     * Returns this element's annotation for the specified type if
     * such an annotation is <em>present</em>, else null.
     *
     * @param <T> the type of the annotation to query for and return if present
     * @param annotationClass the Class object corresponding to the
     *        annotation type
     * @return this element's annotation for the specified annotation type if
     *     present on this element, else null
     * @throws NullPointerException if the given annotation class is null
     * @since 1.5
     */
    <T extends Annotation> T getAnnotation(Class<T> annotationClass);

An example of using the field would be:使用该字段的一个示例是:

if (fcol.getAnnotation(Transient.class) != null)) {
    // do something
}

Assume myObject is an instance of the Entity.假设 myObject 是 Entity 的一个实例。 You have to iterate over all the fields of the class and check if there are fields annotated with @Transient.您必须遍历类的所有字段并检查是否有使用@Transient 注释的字段。 If this call return null then it means the field is not annotated with this annotation.如果此调用返回 null,则表示该字段未使用此注释进行注释。 So you can do whatever you like:所以你可以做任何你喜欢的事情:

Field[] fields = myObject.getClass().getFields();
for (Field field : fields) {
    Transient transientAnnoation = field.getAnnotation(Transient.class);
    if (transientAnnoation  == null) {
        do something
    }
 }
Field[] fields = myObject.getClass().getFields();
  for (Field field : fields) {
    boolean isTransient =   
        field.getDeclaredAnnotation(javax.persistence.Transient.class) 
        == null ? false : true;
  }

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

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