src/share/classes/com/sun/tools/javac/code/AnnoConstruct.java

Tue, 22 Oct 2013 03:36:44 +0200

author
jfranck
date
Tue, 22 Oct 2013 03:36:44 +0200
changeset 2154
ac839d6f4953
parent 2100
1e7ad879f15e
child 2156
f003f09144ff
permissions
-rw-r--r--

8026855: AnnoConstruct.getAnnotationsByType includes inherited indirectly present annotations even when containee type is not inheritable
Summary: In AnnoConstruct.getAnnotationByType() check that the annotation sought after is inherited before looking on supertypes.
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 package com.sun.tools.javac.code;
    27 import java.lang.annotation.Annotation;
    28 import java.lang.annotation.Inherited;
    29 import java.lang.reflect.InvocationTargetException;
    30 import java.lang.reflect.Method;
    32 import javax.lang.model.AnnotatedConstruct;
    34 import com.sun.tools.javac.model.AnnotationProxyMaker;
    35 import com.sun.tools.javac.util.List;
    36 import com.sun.tools.javac.util.ListBuffer;
    38 /**
    39  * Common super type for annotated constructs such as Types and Symbols.
    40  *
    41  * This class should *not* contain any fields since it would have a significant
    42  * impact on the javac memory footprint.
    43  *
    44  * <p><b>This is NOT part of any supported API.
    45  * If you write code that depends on this, you do so at your own
    46  * risk.  This code and its internal interfaces are subject to change
    47  * or deletion without notice.</b></p>
    48  */
    49 public abstract class AnnoConstruct implements AnnotatedConstruct {
    52     // Override to enforce a narrower return type.
    53     @Override
    54     public abstract List<? extends Attribute.Compound> getAnnotationMirrors();
    57     // This method is part of the javax.lang.model API, do not use this in javac code.
    58     protected <A extends Annotation> Attribute.Compound getAttribute(Class<A> annoType) {
    59         String name = annoType.getName();
    61         for (Attribute.Compound anno : getAnnotationMirrors()) {
    62             if (name.equals(anno.type.tsym.flatName().toString()))
    63                 return anno;
    64         }
    66         return null;
    67     }
    70     @SuppressWarnings("unchecked")
    71     protected <A extends Annotation> A[] getInheritedAnnotations(Class<A> annoType) {
    72         return (A[]) java.lang.reflect.Array.newInstance(annoType, 0);  // annoType is the Class for A
    73     }
    76     // This method is part of the javax.lang.model API, do not use this in javac code.
    77     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annoType) {
    79         if (!annoType.isAnnotation())
    80             throw new IllegalArgumentException("Not an annotation type: "
    81                                                + annoType);
    82         // If annoType does not declare a container this is equivalent to wrapping
    83         // getAnnotation(...) in an array.
    84         Class <? extends Annotation> containerType = getContainer(annoType);
    85         if (containerType == null) {
    86             A res = getAnnotation(annoType);
    87             int size = res == null ? 0 : 1;
    89             @SuppressWarnings("unchecked") // annoType is the Class for A
    90             A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
    91             if (res != null)
    92                 arr[0] = res;
    93             return arr;
    94         }
    96         // So we have a containing type
    97         String annoTypeName = annoType.getName();
    98         String containerTypeName = containerType.getName();
    99         int directIndex = -1, containerIndex = -1;
   100         Attribute.Compound direct = null, container = null;
   101         // Find directly (explicit or implicit) present annotations
   102         int index = -1;
   103         for (Attribute.Compound attribute : getAnnotationMirrors()) {
   104             index++;
   105             if (attribute.type.tsym.flatName().contentEquals(annoTypeName)) {
   106                 directIndex = index;
   107                 direct = attribute;
   108             } else if(containerTypeName != null &&
   109                       attribute.type.tsym.flatName().contentEquals(containerTypeName)) {
   110                 containerIndex = index;
   111                 container = attribute;
   112             }
   113         }
   115         // Deal with inherited annotations
   116         if (direct == null && container == null &&
   117                 annoType.isAnnotationPresent(Inherited.class))
   118             return getInheritedAnnotations(annoType);
   120         // Pack them in an array
   121         Attribute[] contained0 = null;
   122         if (container != null)
   123             contained0 = unpackAttributes(container);
   124         ListBuffer<Attribute.Compound> compounds = new ListBuffer<>();
   125         if (contained0 != null) {
   126             for (Attribute a : contained0)
   127                 if (a instanceof Attribute.Compound)
   128                     compounds = compounds.append((Attribute.Compound)a);
   129         }
   130         Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[compounds.size()]);
   132         int size = (direct == null ? 0 : 1) + contained.length;
   133         @SuppressWarnings("unchecked") // annoType is the Class for A
   134         A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
   136         // if direct && container, which is first?
   137         int insert = -1;
   138         int length = arr.length;
   139         if (directIndex >= 0 && containerIndex >= 0) {
   140             if (directIndex < containerIndex) {
   141                 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   142                 insert = 1;
   143             } else {
   144                 arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   145                 insert = 0;
   146                 length--;
   147             }
   148         } else if (directIndex >= 0) {
   149             arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   150             return arr;
   151         } else {
   152             // Only container
   153             insert = 0;
   154         }
   156         for (int i = 0; i + insert < length; i++)
   157             arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);
   159         return arr;
   160     }
   163     // This method is part of the javax.lang.model API, do not use this in javac code.
   164     public <A extends Annotation> A getAnnotation(Class<A> annoType) {
   166         if (!annoType.isAnnotation())
   167             throw new IllegalArgumentException("Not an annotation type: " + annoType);
   169         Attribute.Compound c = getAttribute(annoType);
   170         return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
   171     }
   173     // Needed to unpack the runtime view of containing annotations
   174     private static final Class<? extends Annotation> REPEATABLE_CLASS = initRepeatable();
   175     private static final Method VALUE_ELEMENT_METHOD = initValueElementMethod();
   177     private static Class<? extends Annotation> initRepeatable() {
   178         try {
   179             // Repeatable will not be available when bootstrapping on
   180             // JDK 7 so use a reflective lookup instead of a class
   181             // literal for Repeatable.class.
   182             return Class.forName("java.lang.annotation.Repeatable").asSubclass(Annotation.class);
   183         } catch (ClassNotFoundException | SecurityException e) {
   184             return null;
   185         }
   186     }
   188     private static Method initValueElementMethod() {
   189         if (REPEATABLE_CLASS == null)
   190             return null;
   192         Method m = null;
   193         try {
   194             m = REPEATABLE_CLASS.getMethod("value");
   195             if (m != null)
   196                 m.setAccessible(true);
   197             return m;
   198         } catch (NoSuchMethodException e) {
   199             return null;
   200         }
   201     }
   204     // Helper to getAnnotationsByType
   205     private static Class<? extends Annotation> getContainer(Class<? extends Annotation> annoType) {
   206         // Since we can not refer to java.lang.annotation.Repeatable until we are
   207         // bootstrapping with java 8 we need to get the Repeatable annotation using
   208         // reflective invocations instead of just using its type and element method.
   209         if (REPEATABLE_CLASS != null &&
   210             VALUE_ELEMENT_METHOD != null) {
   211             // Get the Repeatable instance on the annotations declaration
   212             Annotation repeatable = (Annotation)annoType.getAnnotation(REPEATABLE_CLASS);
   213             if (repeatable != null) {
   214                 try {
   215                     // Get the value element, it should be a class
   216                     // indicating the containing annotation type
   217                     @SuppressWarnings("unchecked")
   218                     Class<? extends Annotation> containerType = (Class)VALUE_ELEMENT_METHOD.invoke(repeatable);
   219                     if (containerType == null)
   220                         return null;
   222                     return containerType;
   223                 } catch (ClassCastException | IllegalAccessException | InvocationTargetException e) {
   224                     return null;
   225                 }
   226             }
   227         }
   228         return null;
   229     }
   232     // Helper to getAnnotationsByType
   233     private static Attribute[] unpackAttributes(Attribute.Compound container) {
   234         // We now have an instance of the container,
   235         // unpack it returning an instance of the
   236         // contained type or null
   237         return ((Attribute.Array)container.member(container.type.tsym.name.table.names.value)).values;
   238     }
   240 }

mercurial