src/share/classes/com/sun/tools/javac/model/JavacAnnoConstructs.java

Mon, 18 Mar 2013 18:33:13 -0700

author
jjg
date
Mon, 18 Mar 2013 18:33:13 -0700
changeset 1645
97f6839673d6
child 1709
bae8387d16aa
permissions
-rw-r--r--

8007803: Implement javax.lang.model API for Type Annotations
Reviewed-by: darcy

     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.model;
    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 com.sun.tools.javac.code.Attribute;
    33 import com.sun.tools.javac.code.Kinds;
    34 import com.sun.tools.javac.code.Symbol;
    35 import com.sun.tools.javac.code.Symbol.ClassSymbol;
    36 import com.sun.tools.javac.code.Type;
    37 import com.sun.tools.javac.code.Type.AnnotatedType;
    38 import com.sun.tools.javac.util.ListBuffer;
    39 import static com.sun.tools.javac.code.TypeTag.CLASS;
    41 /**
    42  * Utility methods for operating on annotated constructs.
    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 class JavacAnnoConstructs {
    51     // <editor-fold defaultstate="collapsed" desc="Symbols">
    53     /**
    54      * An internal-use utility that creates a runtime view of an
    55      * annotation. This is the implementation of
    56      * Element.getAnnotation(Class).
    57      */
    58     public static <A extends Annotation> A getAnnotation(Symbol annotated,
    59                                                          Class<A> annoType) {
    60         if (!annoType.isAnnotation())
    61             throw new IllegalArgumentException("Not an annotation type: "
    62                                                + annoType);
    63         Attribute.Compound c;
    64         if (annotated.kind == Kinds.TYP && annotated instanceof ClassSymbol) {
    65             c = getAttributeOnClass((ClassSymbol)annotated, annoType);
    66         } else {
    67             c = getAttribute(annotated, annoType);
    68         }
    69         return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
    70     }
    72     // Helper to getAnnotation[s]
    73     private static <A extends Annotation> Attribute.Compound getAttribute(Symbol annotated,
    74                                                                           Class<A> annoType) {
    75         String name = annoType.getName();
    77         for (Attribute.Compound anno : annotated.getRawAttributes()) {
    78             if (name.equals(anno.type.tsym.flatName().toString()))
    79                 return anno;
    80         }
    82         return null;
    83     }
    85     // Helper to getAnnotation[s]
    86     private static <A extends Annotation> Attribute.Compound getAttributeOnClass(ClassSymbol annotated,
    87                                                                 Class<A> annoType) {
    88         boolean inherited = annoType.isAnnotationPresent(Inherited.class);
    89         Attribute.Compound result = null;
    90         while (annotated.name != annotated.name.table.names.java_lang_Object) {
    91             result = getAttribute(annotated, annoType);
    92             if (result != null || !inherited)
    93                 break;
    94             Type sup = annotated.getSuperclass();
    95             if (!sup.hasTag(CLASS) || sup.isErroneous())
    96                 break;
    97             annotated = (ClassSymbol) sup.tsym;
    98         }
    99         return result;
   100     }
   102     /**
   103      * An internal-use utility that creates a runtime view of
   104      * annotations. This is the implementation of
   105      * Element.getAnnotations(Class).
   106      */
   107     public static <A extends Annotation> A[] getAnnotations(Symbol annotated,
   108                                                             Class<A> annoType) {
   109         if (!annoType.isAnnotation())
   110             throw new IllegalArgumentException("Not an annotation type: "
   111                                                + annoType);
   112         // If annoType does not declare a container this is equivalent to wrapping
   113         // getAnnotation(...) in an array.
   114         Class <? extends Annotation> containerType = getContainer(annoType);
   115         if (containerType == null) {
   116             A res = getAnnotation(annotated, annoType);
   117             int size;
   118             if (res == null) {
   119                 size = 0;
   120             } else {
   121                 size = 1;
   122             }
   123             @SuppressWarnings("unchecked") // annoType is the Class for A
   124             A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
   125             if (res != null)
   126                 arr[0] = res;
   127             return arr;
   128         }
   130         // So we have a containing type
   131         String name = annoType.getName();
   132         String annoTypeName = annoType.getSimpleName();
   133         String containerTypeName = containerType.getSimpleName();
   134         int directIndex = -1, containerIndex = -1;
   135         Attribute.Compound direct = null, container = null;
   136         Attribute.Compound[] rawAttributes = annotated.getRawAttributes().toArray(new Attribute.Compound[0]);
   138         // Find directly present annotations
   139         for (int i = 0; i < rawAttributes.length; i++) {
   140             if (annoTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
   141                 directIndex = i;
   142                 direct = rawAttributes[i];
   143             } else if(containerTypeName != null &&
   144                       containerTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
   145                 containerIndex = i;
   146                 container = rawAttributes[i];
   147             }
   148         }
   150         // Deal with inherited annotations
   151         if (annotated.kind == Kinds.TYP &&
   152                 (annotated instanceof ClassSymbol)) {
   153             ClassSymbol s = (ClassSymbol)annotated;
   154             if (direct == null && container == null) {
   155                 direct = getAttributeOnClass(s, annoType);
   156                 container = getAttributeOnClass(s, containerType);
   158                 // both are inherited and found, put container last
   159                 if (direct != null && container != null) {
   160                     directIndex = 0;
   161                     containerIndex = 1;
   162                 } else if (direct != null) {
   163                     directIndex = 0;
   164                 } else {
   165                     containerIndex = 0;
   166                 }
   167             } else if (direct == null) {
   168                 direct = getAttributeOnClass(s, annoType);
   169                 if (direct != null)
   170                     directIndex = containerIndex + 1;
   171             } else if (container == null) {
   172                 container = getAttributeOnClass(s, containerType);
   173                 if (container != null)
   174                     containerIndex = directIndex + 1;
   175             }
   176         }
   178         // Pack them in an array
   179         Attribute[] contained0 = new Attribute[0];
   180         if (container != null)
   181             contained0 = unpackAttributes(container);
   182         ListBuffer<Attribute.Compound> compounds = ListBuffer.lb();
   183         for (Attribute a : contained0)
   184             if (a instanceof Attribute.Compound)
   185                 compounds = compounds.append((Attribute.Compound)a);
   186         Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[0]);
   188         int size = (direct == null ? 0 : 1) + contained.length;
   189         @SuppressWarnings("unchecked") // annoType is the Class for A
   190         A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
   192         // if direct && container, which is first?
   193         int insert = -1;
   194         int length = arr.length;
   195         if (directIndex >= 0 && containerIndex >= 0) {
   196             if (directIndex < containerIndex) {
   197                 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   198                 insert = 1;
   199             } else {
   200                 arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   201                 insert = 0;
   202                 length--;
   203             }
   204         } else if (directIndex >= 0) {
   205             arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   206             return arr;
   207         } else {
   208             // Only container
   209             insert = 0;
   210         }
   212         for (int i = 0; i + insert < length; i++)
   213             arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);
   215         return arr;
   216     }
   218     // </editor-fold>
   220     // <editor-fold defaultstate="collapsed" desc="Types">
   222     /**
   223      * An internal-use utility that creates a runtime view of an
   224      * annotation. This is the implementation of
   225      * TypeMirror.getAnnotation(Class).
   226      */
   227     public static <A extends Annotation> A getAnnotation(AnnotatedType annotated, Class<A> annoType) {
   228         if (!annoType.isAnnotation())
   229             throw new IllegalArgumentException("Not an annotation type: "
   230                                                + annoType);
   231         Attribute.Compound c = getAttribute(annotated, annoType);
   232         return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
   233     }
   235     // Helper to getAnnotation[s]
   236     private static <A extends Annotation> Attribute.Compound getAttribute(Type annotated,
   237                                                                           Class<A> annoType) {
   238         String name = annoType.getName();
   240         for (Attribute.Compound anno : annotated.getAnnotationMirrors()) {
   241             if (name.equals(anno.type.tsym.flatName().toString()))
   242                 return anno;
   243         }
   245         return null;
   246     }
   248     /**
   249      * An internal-use utility that creates a runtime view of
   250      * annotations. This is the implementation of
   251      * TypeMirror.getAnnotationsByType(Class).
   252      */
   253     public static <A extends Annotation> A[] getAnnotationsByType(AnnotatedType annotated, Class<A> annoType) {
   254         if (!annoType.isAnnotation())
   255             throw new IllegalArgumentException("Not an annotation type: "
   256                                                + annoType);
   257         // If annoType does not declare a container this is equivalent to wrapping
   258         // getAnnotation(...) in an array.
   259         Class <? extends Annotation> containerType = getContainer(annoType);
   260         if (containerType == null) {
   261             A res = getAnnotation(annotated, annoType);
   262             int size;
   263             if (res == null) {
   264                 size = 0;
   265             } else {
   266                 size = 1;
   267             }
   268             @SuppressWarnings("unchecked") // annoType is the Class for A
   269             A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
   270             if (res != null)
   271                 arr[0] = res;
   272             return arr;
   273         }
   275         // So we have a containing type
   276         String name = annoType.getName();
   277         String annoTypeName = annoType.getSimpleName();
   278         String containerTypeName = containerType.getSimpleName();
   279         int directIndex = -1, containerIndex = -1;
   280         Attribute.Compound direct = null, container = null;
   281         Attribute.Compound[] rawAttributes = annotated.getAnnotationMirrors().toArray(new Attribute.Compound[0]);
   283         // Find directly present annotations
   284         for (int i = 0; i < rawAttributes.length; i++) {
   285             if (annoTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
   286                 directIndex = i;
   287                 direct = rawAttributes[i];
   288             } else if(containerTypeName != null &&
   289                       containerTypeName.equals(rawAttributes[i].type.tsym.flatName().toString())) {
   290                 containerIndex = i;
   291                 container = rawAttributes[i];
   292             }
   293         }
   295         // Pack them in an array
   296         Attribute[] contained0 = new Attribute[0];
   297         if (container != null)
   298             contained0 = unpackAttributes(container);
   299         ListBuffer<Attribute.Compound> compounds = ListBuffer.lb();
   300         for (Attribute a : contained0) {
   301             if (a instanceof Attribute.Compound)
   302                 compounds = compounds.append((Attribute.Compound)a);
   303         }
   304         Attribute.Compound[] contained = compounds.toArray(new Attribute.Compound[0]);
   306         int size = (direct == null ? 0 : 1) + contained.length;
   307         @SuppressWarnings("unchecked") // annoType is the Class for A
   308         A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
   310         // if direct && container, which is first?
   311         int insert = -1;
   312         int length = arr.length;
   313         if (directIndex >= 0 && containerIndex >= 0) {
   314             if (directIndex < containerIndex) {
   315                 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   316                 insert = 1;
   317             } else {
   318                 arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   319                 insert = 0;
   320                 length--;
   321             }
   322         } else if (directIndex >= 0) {
   323             arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
   324             return arr;
   325         } else {
   326             // Only container
   327             insert = 0;
   328         }
   330         for (int i = 0; i + insert < length; i++)
   331             arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);
   333         return arr;
   334     }
   336     // </editor-fold>
   338     // <editor-fold defaultstate="collapsed" desc="Container support">
   340     // Needed to unpack the runtime view of containing annotations
   341     private static final Class<? extends Annotation> REPEATABLE_CLASS = initRepeatable();
   342     private static final Method VALUE_ELEMENT_METHOD = initValueElementMethod();
   344     private static Class<? extends Annotation> initRepeatable() {
   345         try {
   346             // Repeatable will not be available when bootstrapping on
   347             // JDK 7 so use a reflective lookup instead of a class
   348             // literal for Repeatable.class.
   349             return Class.forName("java.lang.annotation.Repeatable").asSubclass(Annotation.class);
   350         } catch (ClassNotFoundException e) {
   351             return null;
   352         } catch (SecurityException e) {
   353             return null;
   354         }
   355     }
   357     private static Method initValueElementMethod() {
   358         if (REPEATABLE_CLASS == null)
   359             return null;
   361         Method m = null;
   362         try {
   363             m = REPEATABLE_CLASS.getMethod("value");
   364             if (m != null)
   365                 m.setAccessible(true);
   366             return m;
   367         } catch (NoSuchMethodException e) {
   368             return null;
   369         }
   370     }
   372     // Helper to getAnnotations
   373     private static Class<? extends Annotation> getContainer(Class<? extends Annotation> annoType) {
   374         // Since we can not refer to java.lang.annotation.Repeatable until we are
   375         // bootstrapping with java 8 we need to get the Repeatable annotation using
   376         // reflective invocations instead of just using its type and element method.
   377         if (REPEATABLE_CLASS != null &&
   378             VALUE_ELEMENT_METHOD != null) {
   379             // Get the Repeatable instance on the annotations declaration
   380             Annotation repeatable = (Annotation)annoType.getAnnotation(REPEATABLE_CLASS);
   381             if (repeatable != null) {
   382                 try {
   383                     // Get the value element, it should be a class
   384                     // indicating the containing annotation type
   385                     @SuppressWarnings("unchecked")
   386                     Class<? extends Annotation> containerType = (Class)VALUE_ELEMENT_METHOD.invoke(repeatable);
   387                     if (containerType == null)
   388                         return null;
   390                     return containerType;
   391                 } catch (ClassCastException e) {
   392                     return null;
   393                 } catch (IllegalAccessException e) {
   394                     return null;
   395                 } catch (InvocationTargetException e ) {
   396                     return null;
   397                 }
   398             }
   399         }
   400         return null;
   401     }
   403     // Helper to getAnnotations
   404     private static Attribute[] unpackAttributes(Attribute.Compound container) {
   405         // We now have an instance of the container,
   406         // unpack it returning an instance of the
   407         // contained type or null
   408         return ((Attribute.Array)container.member(container.type.tsym.name.table.names.value)).values;
   409     }
   411     // </editor-fold>
   412 }

mercurial