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

The following examples show how to use java.lang.reflect.AnnotatedElement#getAnnotations() . 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: TransactionalAdvice.java    From alfresco-mvc with Apache License 2.0 6 votes vote down vote up
private AlfrescoTransaction parseAnnotation(AnnotatedElement ae) {
	AlfrescoTransaction ann = ae.getAnnotation(AlfrescoTransaction.class);
	if (ann == null) {
		for (Annotation metaAnn : ae.getAnnotations()) {
			ann = metaAnn.annotationType().getAnnotation(AlfrescoTransaction.class);
			if (ann != null) {
				break;
			}
		}
	}
	if (ann != null) {
		return parseAnnotation(ann);
	} else {
		return null;
	}
}
 
Example 2
Source File: AuthenticationAdvice.java    From alfresco-mvc with Apache License 2.0 6 votes vote down vote up
private AlfrescoAuthentication parseAnnotation(AnnotatedElement ae) {
	AlfrescoAuthentication ann = ae.getAnnotation(AlfrescoAuthentication.class);
	if (ann == null) {
		for (Annotation metaAnn : ae.getAnnotations()) {
			ann = metaAnn.annotationType().getAnnotation(AlfrescoAuthentication.class);
			if (ann != null) {
				break;
			}
		}
	}
	if (ann != null) {
		return parseAnnotation(ann);
	} else {
		return null;
	}
}
 
Example 3
Source File: CachingAnnotationsAspect.java    From spring-cache-self-refresh with MIT License 6 votes vote down vote up
/**
 * Parses all annotations declared on the Method
 * 
 * @param ae
 * @param annotationType
 *            Annotation type to look for
 * @return
 */
private static <T extends Annotation> List<T> getMethodAnnotations(AnnotatedElement ae, Class<T> annotationType) {
	List<T> anns = new ArrayList<T>(2);
	// look for raw annotation
	T ann = ae.getAnnotation(annotationType);
	if (ann != null) {
		anns.add(ann);
	}
	// look for meta-annotations
	for (Annotation metaAnn : ae.getAnnotations()) {
		ann = metaAnn.annotationType().getAnnotation(annotationType);
		if (ann != null) {
			anns.add(ann);
		}
	}
	return (anns.isEmpty() ? null : anns);
}
 
Example 4
Source File: AnnotationUtils.java    From dolphin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void process(AnnotatedElement annotatedElement) {
	if (this.visited.add(annotatedElement)) {
		for (Annotation ann : annotatedElement.getAnnotations()) {
			if (ObjectUtils.nullSafeEquals(this.annotationType, ann.annotationType())) {
				this.result.add((A) ann);
			}
			else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, ann.annotationType())) {
				this.result.addAll(getValue(ann));
			}
			else if (!isInJavaLangAnnotationPackage(ann)) {
				process(ann.annotationType());
			}
		}
	}
}
 
Example 5
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 6
Source File: ReflectionHelper.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if a Class or Method are annotated with the given annotation
 *
 * @param elem                 the Class or Method to reflect on
 * @param annotationType       the annotation type
 * @param checkMetaAnnotations check for meta annotations
 * @return true if annotations is present
 */
public static boolean hasAnnotation(AnnotatedElement elem, Class<? extends Annotation> annotationType,
                                    boolean checkMetaAnnotations) {
    if (elem.isAnnotationPresent(annotationType)) {
        return true;
    }
    if (checkMetaAnnotations) {
        for (Annotation a : elem.getAnnotations()) {
            for (Annotation meta : a.annotationType().getAnnotations()) {
                if (meta.annotationType().getName().equals(annotationType.getName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 7
Source File: Annotations.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Find all "whitelisted" annotations for given element.
 *
 * @param annotatedElement The target element.
 * @return All found annotations.
 */
private static Collection<Annotation> findWhitelistedElementAnnotations(AnnotatedElement annotatedElement) {
	final Annotation[] annotations = annotatedElement.getAnnotations();
	final List<Annotation> whitelistedAnnotations = new ArrayList<>(annotations.length);

	for (Annotation annotation : annotations) {
		final Class<? extends Annotation> annotationType = annotation.annotationType();
		if (shouldScan(annotationType)) {
			whitelistedAnnotations.add(annotation);
		}
	}

	return whitelistedAnnotations;
}
 
Example 8
Source File: MetaInfo.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public MetaInfo withAnnotations( AnnotatedElement annotatedElement )
{
    for( Annotation annotation : annotatedElement.getAnnotations() )
    {
        if( !ignored.contains( annotation.annotationType() )
            && get( annotation.annotationType() ) == null )
        {
            set( annotation );
        }
    }
    return this;
}
 
Example 9
Source File: Property.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void addAnnotationsToMap(
		Map<Class<? extends Annotation>, Annotation> annotationMap, AnnotatedElement object) {

	if (object != null) {
		for (Annotation annotation : object.getAnnotations()) {
			annotationMap.put(annotation.annotationType(), annotation);
		}
	}
}
 
Example 10
Source File: AnnotationSizeOfFilter.java    From sizeof with Apache License 2.0 5 votes vote down vote up
private <T extends Annotation> T getAnnotationOn(AnnotatedElement element, Class<T> referenceAnnotation, Pattern matchingAnnotationPattern) {
    T matchingAnnotation = null;
    Annotation[] annotations = element.getAnnotations();
    for (Annotation annotation : annotations) {
        if (validateCustomAnnotationPattern(annotation.annotationType().getName(), matchingAnnotationPattern)) {
            if (matchingAnnotation != null) {
                throw new IllegalStateException("You are not allowed to use more than one @" + referenceAnnotation.getName()
                                                + " annotations for the same element : "
                                                + element.toString());
            }
            matchingAnnotation = AnnotationProxyFactory.getAnnotationProxy(annotation, referenceAnnotation);
        }
    }
    return matchingAnnotation;
}
 
Example 11
Source File: AnnotationUtils.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private static <A extends Annotation> A getDeclaredAnnotation(AnnotatedElement element, Class<A> annotationType) {
    for (Annotation annotation: element.getAnnotations()) {
        if(annotation.annotationType().equals(annotationType)) {
            return (A) annotation;
        }
    }
    return null;
}
 
Example 12
Source File: MockBean.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
private static Set<Annotation> getScopes(AnnotatedElement element) {
    Set<Annotation> scopes = new HashSet<>();
    for (Annotation annotation : element.getAnnotations()) {
        if (annotation.annotationType().isAnnotationPresent(Scope.class) || annotation.annotationType().isAnnotationPresent(NormalScope.class)) {
            scopes.add(annotation);
        }
    }
    return scopes;
}
 
Example 13
Source File: ClassDescription.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void processType(AnnotatedElement type) {
	String suffix="";
	String prefix="";
	if(excludePublicElementsFromDeclared()) {
		suffix=" (excluding public)";
		prefix="public ";
	}
	Annotation[] annotations=type.getAnnotations();

	super.addTitle("AnnotatedElement");
	super.addMultiField(prefix+"annotations", wrapElementArray(annotations));
	super.addMultiField("declared annotations"+suffix, wrapElements(publicElementFilter(annotations,type.getDeclaredAnnotations())));
}
 
Example 14
Source File: ImplementationDependency.java    From presto with Apache License 2.0 5 votes vote down vote up
static Optional<Annotation> getImplementationDependencyAnnotation(AnnotatedElement element)
{
    if (!containsImplementationDependencyAnnotation(element.getAnnotations())) {
        return Optional.empty();
    }
    Annotation[] annotations = element.getAnnotations();
    checkArgument(annotations.length == 1, "Meta parameters may only have a single annotation [%s]", element);
    return Optional.of(annotations[0]);
}
 
Example 15
Source File: Introspector.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static Descriptor descriptorForElement(final AnnotatedElement elmt) {
    if (elmt == null)
        return ImmutableDescriptor.EMPTY_DESCRIPTOR;
    final Annotation[] annots = elmt.getAnnotations();
    return descriptorForAnnotations(annots);
}
 
Example 16
Source File: AnnotationUtils.java    From simple-robot-core with Apache License 2.0 4 votes vote down vote up
/**
 * 从某个类上获取注解对象,注解可以深度递归
 * 如果存在多个继承注解,则优先获取浅层第一个注解,如果浅层不存在,则返回第一个获取到的注解
 * 请尽可能保证仅存在一个或者一种继承注解,否则获取到的类型将不可控
 *
 * @param from           获取注解的某个类
 * @param annotationType 想要获取的注解类型
 * @param ignored        获取注解列表的时候的忽略列表
 * @return 获取到的第一个注解对象
 */
public static <T extends Annotation> T getAnnotation(AnnotatedElement from, Class<T> annotationType, Class<T>... ignored) {
    // 首先尝试获取缓存
    T cache = getCache(from, annotationType);
    if(cache != null){
        return cache;
    }

    if(isNull(from, annotationType)){
        return null;
    }


    //先尝试直接获取
    T annotation = from.getAnnotation(annotationType);

    //如果存在直接返回,否则查询
    if (annotation != null) {
        saveCache(from, annotation);
        return annotation;
    }

    // 获取target注解
    Target target = annotationType.getAnnotation(Target.class);
    // 判断这个注解能否标注在其他注解上,如果不能,则不再深入获取
    boolean annotationable = false;
    if (target != null) {
        for (ElementType elType : target.value()) {
            if (elType == ElementType.TYPE || elType == ElementType.ANNOTATION_TYPE) {
                annotationable = true;
                break;
            }
        }
    }

    Annotation[] annotations = from.getAnnotations();
    annotation = annotationable ? getAnnotationFromArrays(annotations, annotationType, ignored) : null;


    // 如果还是获取不到,看看查询的注解类型有没有对应的ByNameType
    if (annotation == null) {
        annotation = getByNameAnnotation(from, annotationType);
    }

    // 如果无法通过注解本身所指向的byName注解获取,看看有没有反向指向此类型的注解
    // 此情况下不进行深层获取
    if(annotation == null){
        annotation = getAnnotationFromByNames(annotations, annotationType);
    }

    // 如果最终不是null,计入缓存
    if(annotation != null){
        saveCache(from, annotation);
    }else{
        nullCache(from, annotationType);
    }

    return annotation;
}
 
Example 17
Source File: Introspector.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static Descriptor descriptorForElement(final AnnotatedElement elmt) {
    if (elmt == null)
        return ImmutableDescriptor.EMPTY_DESCRIPTOR;
    final Annotation[] annots = elmt.getAnnotations();
    return descriptorForAnnotations(annots);
}
 
Example 18
Source File: Introspector.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static Descriptor descriptorForElement(final AnnotatedElement elmt) {
    if (elmt == null)
        return ImmutableDescriptor.EMPTY_DESCRIPTOR;
    final Annotation[] annots = elmt.getAnnotations();
    return descriptorForAnnotations(annots);
}
 
Example 19
Source File: AnnotatedElementUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Perform the search algorithm for the {@link #searchWithGetSemantics}
 * method, avoiding endless recursion by tracking which annotated elements
 * have already been <em>visited</em>.
 * <p>The {@code metaDepth} parameter is explained in the
 * {@link Processor#process process()} method of the {@link Processor} API.
 * @param element the annotated element
 * @param annotationTypes the annotation types to find
 * @param annotationName the fully qualified class name of the annotation
 * type to find (as an alternative to {@code annotationType})
 * @param containerType the type of the container that holds repeatable
 * annotations, or {@code null} if the annotation is not repeatable
 * @param processor the processor to delegate to
 * @param visited the set of annotated elements that have already been visited
 * @param metaDepth the meta-depth of the annotation
 * @return the result of the processor (potentially {@code null})
 */
@Nullable
private static <T> T searchWithGetSemantics(AnnotatedElement element,
		Set<Class<? extends Annotation>> annotationTypes, @Nullable String annotationName,
		@Nullable Class<? extends Annotation> containerType, Processor<T> processor,
		Set<AnnotatedElement> visited, int metaDepth) {

	if (visited.add(element)) {
		try {
			// Start searching within locally declared annotations
			List<Annotation> declaredAnnotations = Arrays.asList(AnnotationUtils.getDeclaredAnnotations(element));
			T result = searchWithGetSemanticsInAnnotations(element, declaredAnnotations,
					annotationTypes, annotationName, containerType, processor, visited, metaDepth);
			if (result != null) {
				return result;
			}

			if (element instanceof Class) {  // otherwise getAnnotations doesn't return anything new
				Class<?> superclass = ((Class<?>) element).getSuperclass();
				if (superclass != null && superclass != Object.class) {
					List<Annotation> inheritedAnnotations = new LinkedList<>();
					for (Annotation annotation : element.getAnnotations()) {
						if (!declaredAnnotations.contains(annotation)) {
							inheritedAnnotations.add(annotation);
						}
					}
					// Continue searching within inherited annotations
					result = searchWithGetSemanticsInAnnotations(element, inheritedAnnotations,
							annotationTypes, annotationName, containerType, processor, visited, metaDepth);
					if (result != null) {
						return result;
					}
				}
			}
		}
		catch (Throwable ex) {
			AnnotationUtils.handleIntrospectionFailure(element, ex);
		}
	}

	return null;
}
 
Example 20
Source File: MPBase.java    From dx-java with MIT License 4 votes vote down vote up
/**
 * Iterates the annotations of the entity method implementation, it validates that only one method annotation
 * is used in the entity implementation method.
 *
 * @param element           The annotated method of the entity
 * @return                  a hashmap with keys 'method' and 'path'
 * @throws MPException
 */
private static Map<String, Object> getRestInformation(AnnotatedElement element) throws MPException{
    if (element.getAnnotations().length == 0) {
        throw new MPException("No rest method found");
    }

    Map<String, Object> hashAnnotation = new HashMap<String, Object>();
    for (Annotation annotation : element.getAnnotations()) {
        if (annotation instanceof DELETE) {
            DELETE delete = (DELETE) annotation;
            if (StringUtils.isEmpty(delete.path())) {
                throw new MPException("Path not found for DELETE method");
            }
            hashAnnotation = fillHashAnnotations(
                    hashAnnotation,
                    HttpMethod.DELETE,
                    delete.path(),
                    null,
                    delete.retries(),
                    delete.connectionTimeout(),
                    delete.connectionRequestTimeout(),
                    delete.socketTimeout());

        } else if (annotation instanceof GET) {
            GET get = (GET) annotation;
            if (StringUtils.isEmpty(get.path())) {
                throw new MPException("Path not found for GET method");
            }
            hashAnnotation = fillHashAnnotations(
                    hashAnnotation,
                    HttpMethod.GET,
                    get.path(),
                    null,
                    get.retries(),
                    get.connectionTimeout(),
                    get.connectionRequestTimeout(),
                    get.socketTimeout());

        } else if (annotation instanceof POST) {
            POST post = (POST) annotation;
            if (StringUtils.isEmpty(post.path())) {
                throw new MPException("Path not found for POST method");
            }
            hashAnnotation = fillHashAnnotations(
                    hashAnnotation,
                    HttpMethod.POST,
                    post.path(),
                    post.payloadType(),
                    post.retries(),
                    post.connectionTimeout(),
                    post.connectionRequestTimeout(),
                    post.socketTimeout());

        } else if (annotation instanceof PUT) {
            PUT put = (PUT) annotation;
            if (StringUtils.isEmpty(put.path())) {
                throw new MPException("Path not found for PUT method");
            }
            hashAnnotation = fillHashAnnotations(
                    hashAnnotation,
                    HttpMethod.PUT,
                    put.path(),
                    put.payloadType(),
                    put.retries(),
                    put.connectionTimeout(),
                    put.connectionRequestTimeout(),
                    put.socketTimeout());
        }
    }
    return hashAnnotation;
}