| 1 | package net.sourceforge.retroweaver.runtime.java.lang; |
| 2 | |
| 3 | import java.lang.annotation.Annotation; |
| 4 | |
| 5 | /** |
| 6 | * A mirror of java.lang.Package |
| 7 | * |
| 8 | * @author Toby Reyelts Date: Feb 20, 2005 Time: 11:50:47 PM |
| 9 | */ |
| 10 | public class Package_ { |
| 11 | |
| 12 | private Package_() { |
| 13 | // private constructor |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * Implementation notes: |
| 18 | * --------------------- |
| 19 | * <p/> |
| 20 | * Package annotations are a little different from other annotations. The java compiler writes |
| 21 | * them into a synthetic interface named, <package-name>.package-info. Here, we implicitly load that |
| 22 | * class and pass it onto Class_ when asked for annotation information on a package. |
| 23 | * <p/> |
| 24 | * |
| 25 | */ |
| 26 | private static Class getPackageAnnotationClass(final Package p) { |
| 27 | try { |
| 28 | return Class.forName(p.getName() + ".package-info"); |
| 29 | } catch (ClassNotFoundException e) { |
| 30 | return null; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // Provide AnnotatedElement methods |
| 35 | |
| 36 | // Returns this element's annotation for the specified type if such an |
| 37 | // annotation is present, else null. |
| 38 | public static <T extends Annotation> T getAnnotation(final Package p, final Class<T> annotationType) { |
| 39 | final Class c = getPackageAnnotationClass(p); |
| 40 | if (c == null) { |
| 41 | return null; |
| 42 | } else { |
| 43 | return (T) c.getAnnotation(annotationType); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[] {}; |
| 48 | |
| 49 | // Returns all annotations present on this element. |
| 50 | public static Annotation[] getAnnotations(final Package p) { |
| 51 | final Class c = getPackageAnnotationClass(p); |
| 52 | if (c == null) { |
| 53 | return EMPTY_ANNOTATION_ARRAY; // NOPMD by xlv |
| 54 | } else { |
| 55 | return c.getAnnotations(); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Returns all annotations that are directly present on this element. |
| 60 | public static Annotation[] getDeclaredAnnotations(final Package p) { |
| 61 | final Class c = getPackageAnnotationClass(p); |
| 62 | if (c == null) { |
| 63 | return EMPTY_ANNOTATION_ARRAY; // NOPMD by xlv |
| 64 | } else { |
| 65 | return c.getDeclaredAnnotations(); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // Returns true if an annotation for the specified type is present on this |
| 70 | // element, else false. |
| 71 | public static boolean isAnnotationPresent(final Package p, final Class<? extends Annotation> annotationType) { |
| 72 | final Class c = getPackageAnnotationClass(p); |
| 73 | if (c == null) { |
| 74 | return false; |
| 75 | } else { |
| 76 | return c.isAnnotationPresent(annotationType); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | } |