Java Code Examples for java.lang.reflect.AnnotatedElement#getDeclaredAnnotations()

The following examples show how to use java.lang.reflect.AnnotatedElement#getDeclaredAnnotations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotationUtils.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void process(AnnotatedElement element) {
    if (this.visited.add(element)) {
        try {
            Annotation[] annotations = (this.declaredMode ? element.getDeclaredAnnotations() : element.getAnnotations());
            for (Annotation ann : annotations) {
                Class<? extends Annotation> currentAnnotationType = ann.annotationType();
                if (Objects.equals(this.annotationType, currentAnnotationType)) {
                    this.result.add((A) ann);
                } else if (Objects.equals(this.containerAnnotationType, currentAnnotationType)) {
                    this.result.addAll(getValue(element, ann));
                } else if (!isInJavaLangAnnotationPackage(ann)) {
                    process(currentAnnotationType);
                }
            }
        } catch (Throwable ex) {
            handleIntrospectionFailure(element, ex);
        }
    }
}
 
Example 2
Source File: AnnotationUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void process(AnnotatedElement element) {
	if (this.visited.add(element)) {
		try {
			Annotation[] annotations = (this.declaredMode ? element.getDeclaredAnnotations() : element.getAnnotations());
			for (Annotation ann : annotations) {
				Class<? extends Annotation> currentAnnotationType = ann.annotationType();
				if (ObjectUtils.nullSafeEquals(this.annotationType, currentAnnotationType)) {
					this.result.add(synthesizeAnnotation((A) ann, element));
				}
				else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, currentAnnotationType)) {
					this.result.addAll(getValue(element, ann));
				}
				else if (!isInJavaLangAnnotationPackage(currentAnnotationType)) {
					process(currentAnnotationType);
				}
			}
		}
		catch (Throwable ex) {
			handleIntrospectionFailure(element, ex);
		}
	}
}
 
Example 3
Source File: AnnotationUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void process(AnnotatedElement element) {
	if (this.visited.add(element)) {
		try {
			Annotation[] annotations = (this.declaredMode ? element.getDeclaredAnnotations() : element.getAnnotations());
			for (Annotation ann : annotations) {
				Class<? extends Annotation> currentAnnotationType = ann.annotationType();
				if (ObjectUtils.nullSafeEquals(this.annotationType, currentAnnotationType)) {
					this.result.add(synthesizeAnnotation((A) ann, element));
				}
				else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, currentAnnotationType)) {
					this.result.addAll(getValue(element, ann));
				}
				else if (!isInJavaLangAnnotationPackage(ann)) {
					process(currentAnnotationType);
				}
			}
		}
		catch (Exception ex) {
			handleIntrospectionFailure(element, ex);
		}
	}
}
 
Example 4
Source File: WebServerValidator.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private boolean isActiveAnnotationRec(AnnotatedElement annotated,
                                       Set<Class<?>> activeAnnTypes,
                                       Set<AnnotatedElement> checkedTypes)
{
  if (annotated == null || checkedTypes.contains(annotated)) {
    return false;
  }

  checkedTypes.add(annotated);

  for (Annotation ann : annotated.getDeclaredAnnotations()) {
    if (activeAnnTypes.contains(ann.annotationType())) {
      return true;
    }

    if (ann.annotationType() != annotated
        && isActiveAnnotationRec(ann.annotationType(),
                                 activeAnnTypes,
                                 checkedTypes)) {
      return true;
    }
  }

  return false;
}
 
Example 5
Source File: AnnotationUtil.java    From java-di with Apache License 2.0 6 votes vote down vote up
/**
 * Return declared annotation with type `annoClass` from
 * an {@link AnnotatedElement}.
 *
 * @param annotatedElement
 *      the annotated element (could be class, method or field)
 * @param annoClass
 *      the annotation class
 * @param <T>
 *      the generic type of the annotation class
 * @return
 *      the annotation instance or `null` if not found
 */
public static <T extends Annotation> T declaredAnnotation(
        AnnotatedElement annotatedElement,
        Class<T> annoClass
) {
    Annotation[] aa = annotatedElement.getDeclaredAnnotations();
    if (null == aa) {
        return null;
    }
    for (Annotation a : aa) {
        if (annoClass.isInstance(a)) {
            return (T) a;
        }
    }
    return null;
}
 
Example 6
Source File: AnnotationUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all annotations of the {@code annotationType} searching from the specified {@code element}.
 * The search range depends on the specified {@link FindOption}s.
 *
 * @param element the {@link AnnotatedElement} to find annotations
 * @param annotationType the type of the annotation to find
 * @param findOptions the options to be applied when finding annotations
 */
static <T extends Annotation> List<T> find(AnnotatedElement element, Class<T> annotationType,
                                           EnumSet<FindOption> findOptions) {
    requireNonNull(element, "element");
    requireNonNull(annotationType, "annotationType");

    final Builder<T> builder = new Builder<>();

    // Repeatable is not a repeatable. So the length of the returning array is 0 or 1.
    final Repeatable[] repeatableAnnotations = annotationType.getAnnotationsByType(Repeatable.class);
    final Class<? extends Annotation> containerType =
            repeatableAnnotations.length > 0 ? repeatableAnnotations[0].value() : null;

    for (final AnnotatedElement e : resolveTargetElements(element, findOptions)) {
        for (final Annotation annotation : e.getDeclaredAnnotations()) {
            if (findOptions.contains(FindOption.LOOKUP_META_ANNOTATIONS)) {
                findMetaAnnotations(builder, annotation, annotationType, containerType);
            }
            collectAnnotations(builder, annotation, annotationType, containerType);
        }
    }
    return builder.build();
}
 
Example 7
Source File: AnnotationUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all annotations searching from the specified {@code element}. The search range depends on
 * the specified {@link FindOption}s and the specified {@code collectingFilter} decides whether
 * an annotation is collected or not.
 *
 * @param element the {@link AnnotatedElement} to find annotations
 * @param findOptions the options to be applied when retrieving annotations
 * @param collectingFilter the predicate which decides whether the annotation is to be collected or not
 */
static List<Annotation> getAnnotations(AnnotatedElement element, EnumSet<FindOption> findOptions,
                                       Predicate<Annotation> collectingFilter) {
    requireNonNull(element, "element");
    requireNonNull(collectingFilter, "collectingFilter");

    final Builder<Annotation> builder = new Builder<>();

    for (final AnnotatedElement e : resolveTargetElements(element, findOptions)) {
        for (final Annotation annotation : e.getDeclaredAnnotations()) {
            if (findOptions.contains(FindOption.LOOKUP_META_ANNOTATIONS)) {
                getMetaAnnotations(builder, annotation, collectingFilter);
            }
            if (collectingFilter.test(annotation)) {
                builder.add(annotation);
            }
        }
    }
    return builder.build();
}
 
Example 8
Source File: ExportedObject.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private String getAnnotations(AnnotatedElement c) {
    String ans = "";
    for (Annotation a : c.getDeclaredAnnotations()) {
        Class t = a.annotationType();
        String value = "";
        try {
            Method m = t.getMethod("value");
            value = m.invoke(a).toString();
        } catch (NoSuchMethodException NSMe) {
        } catch (InvocationTargetException ITe) {
        } catch (IllegalAccessException IAe) {
        }

        ans += "  <annotation name=\"" + AbstractConnection.dollar_pattern.matcher(t.getName()).replaceAll(".") + "\" value=\"" + value + "\" />\n";
    }
    return ans;
}
 
Example 9
Source File: AnnotationsScanner.java    From spring-analysis-note with MIT License 5 votes vote down vote up
static Annotation[] getDeclaredAnnotations(AnnotatedElement source, boolean defensive) {
	boolean cached = false;
	Annotation[] annotations = declaredAnnotationCache.get(source);
	if (annotations != null) {
		cached = true;
	}
	else {
		annotations = source.getDeclaredAnnotations();
		if (annotations.length != 0) {
			boolean allIgnored = true;
			for (int i = 0; i < annotations.length; i++) {
				Annotation annotation = annotations[i];
				if (isIgnorable(annotation.annotationType()) ||
						!AttributeMethods.forAnnotationType(annotation.annotationType()).isValid(annotation)) {
					annotations[i] = null;
				}
				else {
					allIgnored = false;
				}
			}
			annotations = (allIgnored ? NO_ANNOTATIONS : annotations);
			if (source instanceof Class || source instanceof Member) {
				declaredAnnotationCache.put(source, annotations);
				cached = true;
			}
		}
	}
	if (!defensive || annotations.length == 0 || !cached) {
		return annotations;
	}
	return annotations.clone();
}
 
Example 10
Source File: AnnotationUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Retrieve a potentially cached array of declared annotations for the
 * given element.
 * @param element the annotated element to introspect
 * @return a potentially cached array of declared annotations
 * (only for internal iteration purposes, not for external exposure)
 * @since 5.1
 */
static Annotation[] getDeclaredAnnotations(AnnotatedElement element) {
	if (element instanceof Class || element instanceof Member) {
		// Class/Field/Method/Constructor returns a defensively cloned array from getDeclaredAnnotations.
		// Since we use our result for internal iteration purposes only, it's safe to use a shared copy.
		return declaredAnnotationsCache.computeIfAbsent(element, AnnotatedElement::getDeclaredAnnotations);
	}
	return element.getDeclaredAnnotations();
}
 
Example 11
Source File: AnnotationFinder.java    From micrometer with Apache License 2.0 5 votes vote down vote up
/**
 * The default implementation performs a simple search for a declared annotation matching the search type.
 * Spring provides a more sophisticated annotation search utility that matches on meta-annotations as well.
 *
 * @param annotatedElement The element to search.
 * @param annotationType   The annotation type class.
 * @param <A>              Annotation type to search for.
 * @return A matching annotation.
 */
@SuppressWarnings("unchecked")
default <A extends Annotation> A findAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) {
    Annotation[] anns = annotatedElement.getDeclaredAnnotations();
    for (Annotation ann : anns) {
        if (ann.annotationType() == annotationType) {
            return (A) ann;
        }
    }
    return null;
}
 
Example 12
Source File: ReflectionTypeFactory.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void createAnnotationValues(final AnnotatedElement annotated, final JvmAnnotationTarget result) {
	Annotation[] declaredAnnotations = annotated.getDeclaredAnnotations();
	if (declaredAnnotations.length != 0) {
		InternalEList<JvmAnnotationReference> annotations = (InternalEList<JvmAnnotationReference>)result.getAnnotations();
		for (Annotation annotation : declaredAnnotations) {
			annotations.addUnique(createAnnotationReference(annotation));
		}
	}
}
 
Example 13
Source File: ClassAnalyze.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
/**
 * 解析注解信息。
 */
private static void parseAnnotation(AnnotatedElement ae) {
    Annotation[] ans = ae.getDeclaredAnnotations();
    for (Annotation annotation : ans) {
        log(annotation.toString());
    }
}
 
Example 14
Source File: AnnotatedElementFilterTest.java    From revapi with Apache License 2.0 4 votes vote down vote up
private static int getNumberOfAnnotationsOn(AnnotatedElement element) {
    return element.getDeclaredAnnotations().length;
}
 
Example 15
Source File: GeciAnnotationTools.java    From javageci with Apache License 2.0 2 votes vote down vote up
/**
 * @param element the annotated element for which we need the
 *                annotations
 * @return a stream of the annotations used on the {@code element}.
 * In case any of the annotations is a collection of repeated
 * annotations then the repeated annotations will be returned
 * instead of the collecting annotations. I.e.: if an element has a
 * {@code Gecis} annotation, which is never used directly in the
 * source code, but is put into the byte code by the compiler to
 * wrap the repeated {@code Geci} annotations then the stream will
 * contain the {@code Geci} annotations and not the one {@code
 * Gecis}.
 */
private static Stream<Annotation> getDeclaredAnnotationUnwrapped(AnnotatedElement element) {
    final var allAnnotations = element.getDeclaredAnnotations();
    return Arrays.stream(allAnnotations)
        .flatMap(GeciAnnotationTools::getSelfOrRepeated);
}