View Javadoc
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;
26  
27  import java.lang.annotation.Annotation;
28  import java.lang.annotation.Inherited;
29  import java.lang.reflect.InvocationTargetException;
30  import java.lang.reflect.Method;
31  
32  import javax.lang.model.AnnotatedConstruct;
33  
34  import com.sun.tools.javac.model.AnnotationProxyMaker;
35  import com.sun.tools.javac.util.List;
36  import com.sun.tools.javac.util.ListBuffer;
37  
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 {
50  
51  
52      // Override to enforce a narrower return type.
53      @Override
54      public abstract List<? extends Attribute.Compound> getAnnotationMirrors();
55  
56  
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();
60  
61          for (Attribute.Compound anno : getAnnotationMirrors()) {
62              if (name.equals(anno.type.tsym.flatName().toString()))
63                  return anno;
64          }
65  
66          return null;
67      }
68  
69  
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      }
74  
75  
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) {
78  
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;
88  
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          }
95  
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         }
114 
115         // Deal with inherited annotations
116         if (direct == null && container == null &&
117                 annoType.isAnnotationPresent(Inherited.class))
118             return getInheritedAnnotations(annoType);
119 
120         Attribute.Compound[] contained = unpackContained(container);
121 
122         // In case of an empty legacy container we might need to look for
123         // inherited annos as well
124         if (direct == null && contained.length == 0 &&
125                 annoType.isAnnotationPresent(Inherited.class))
126             return getInheritedAnnotations(annoType);
127 
128         int size = (direct == null ? 0 : 1) + contained.length;
129         @SuppressWarnings("unchecked") // annoType is the Class for A
130         A[] arr = (A[])java.lang.reflect.Array.newInstance(annoType, size);
131 
132         // if direct && container, which is first?
133         int insert = -1;
134         int length = arr.length;
135         if (directIndex >= 0 && containerIndex >= 0) {
136             if (directIndex < containerIndex) {
137                 arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
138                 insert = 1;
139             } else {
140                 arr[arr.length - 1] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
141                 insert = 0;
142                 length--;
143             }
144         } else if (directIndex >= 0) {
145             arr[0] = AnnotationProxyMaker.generateAnnotation(direct, annoType);
146             return arr;
147         } else {
148             // Only container
149             insert = 0;
150         }
151 
152         for (int i = 0; i + insert < length; i++)
153             arr[insert + i] = AnnotationProxyMaker.generateAnnotation(contained[i], annoType);
154 
155         return arr;
156     }
157 
158     private Attribute.Compound[] unpackContained(Attribute.Compound container) {
159         // Pack them in an array
160         Attribute[] contained0 = null;
161         if (container != null)
162             contained0 = unpackAttributes(container);
163         ListBuffer<Attribute.Compound> compounds = new ListBuffer<>();
164         if (contained0 != null) {
165             for (Attribute a : contained0)
166                 if (a instanceof Attribute.Compound)
167                     compounds = compounds.append((Attribute.Compound)a);
168         }
169         return compounds.toArray(new Attribute.Compound[compounds.size()]);
170     }
171 
172     // This method is part of the javax.lang.model API, do not use this in javac code.
173     public <A extends Annotation> A getAnnotation(Class<A> annoType) {
174 
175         if (!annoType.isAnnotation())
176             throw new IllegalArgumentException("Not an annotation type: " + annoType);
177 
178         Attribute.Compound c = getAttribute(annoType);
179         return c == null ? null : AnnotationProxyMaker.generateAnnotation(c, annoType);
180     }
181 
182     // Needed to unpack the runtime view of containing annotations
183     private static final Class<? extends Annotation> REPEATABLE_CLASS = initRepeatable();
184     private static final Method VALUE_ELEMENT_METHOD = initValueElementMethod();
185 
186     private static Class<? extends Annotation> initRepeatable() {
187         try {
188             // Repeatable will not be available when bootstrapping on
189             // JDK 7 so use a reflective lookup instead of a class
190             // literal for Repeatable.class.
191             return Class.forName("java.lang.annotation.Repeatable").asSubclass(Annotation.class);
192         } catch (ClassNotFoundException | SecurityException e) {
193             return null;
194         }
195     }
196 
197     private static Method initValueElementMethod() {
198         if (REPEATABLE_CLASS == null)
199             return null;
200 
201         Method m = null;
202         try {
203             m = REPEATABLE_CLASS.getMethod("value");
204             if (m != null)
205                 m.setAccessible(true);
206             return m;
207         } catch (NoSuchMethodException e) {
208             return null;
209         }
210     }
211 
212 
213     // Helper to getAnnotationsByType
214     private static Class<? extends Annotation> getContainer(Class<? extends Annotation> annoType) {
215         // Since we can not refer to java.lang.annotation.Repeatable until we are
216         // bootstrapping with java 8 we need to get the Repeatable annotation using
217         // reflective invocations instead of just using its type and element method.
218         if (REPEATABLE_CLASS != null &&
219             VALUE_ELEMENT_METHOD != null) {
220             // Get the Repeatable instance on the annotations declaration
221             Annotation repeatable = (Annotation)annoType.getAnnotation(REPEATABLE_CLASS);
222             if (repeatable != null) {
223                 try {
224                     // Get the value element, it should be a class
225                     // indicating the containing annotation type
226                     @SuppressWarnings("unchecked")
227                     Class<? extends Annotation> containerType = (Class)VALUE_ELEMENT_METHOD.invoke(repeatable);
228                     if (containerType == null)
229                         return null;
230 
231                     return containerType;
232                 } catch (ClassCastException | IllegalAccessException | InvocationTargetException e) {
233                     return null;
234                 }
235             }
236         }
237         return null;
238     }
239 
240 
241     // Helper to getAnnotationsByType
242     private static Attribute[] unpackAttributes(Attribute.Compound container) {
243         // We now have an instance of the container,
244         // unpack it returning an instance of the
245         // contained type or null
246         return ((Attribute.Array)container.member(container.type.tsym.name.table.names.value)).values;
247     }
248 
249 }