001package org.apache.tapestry5.internal.plastic;
002
003import java.lang.annotation.Annotation;
004import java.lang.annotation.Inherited;
005
006import org.apache.tapestry5.plastic.AnnotationAccess;
007
008/**
009 * Delegating annotation access is used when resolving annotations on a class; it searches the primary
010 * annotation access and if not found there (and {@link Inherited} is on the annotation being searched),
011 * it searches in the inherited access.
012 */
013public class DelegatingAnnotationAccess implements AnnotationAccess
014{
015    private final AnnotationAccess primary;
016
017    private final AnnotationAccess inherited;
018
019    public DelegatingAnnotationAccess(AnnotationAccess primary, AnnotationAccess inherited)
020    {
021        this.primary = primary;
022        this.inherited = inherited;
023    }
024
025    private boolean isInherited(Class<? extends Annotation> annotationType)
026    {
027        return annotationType.getAnnotation(Inherited.class) != null;
028    }
029
030    @Override
031    public <T extends Annotation> boolean hasAnnotation(Class<T> annotationType)
032    {
033        if (primary.hasAnnotation(annotationType))
034            return true;
035
036        return isInherited(annotationType) && inherited.hasAnnotation(annotationType);
037    }
038
039    @Override
040    public <T extends Annotation> T getAnnotation(Class<T> annotationType)
041    {
042        T fromPrimary = primary.getAnnotation(annotationType);
043
044        if (fromPrimary != null)
045            return fromPrimary;
046
047        return isInherited(annotationType) ? inherited.getAnnotation(annotationType) : null;
048    }
049}