    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3;
    018
    019import java.lang.annotation.Annotation;
    020import java.lang.reflect.InvocationTargetException;
    021import java.lang.reflect.Method;
    022import java.util.Arrays;
    023
    024import org.apache.commons.lang3.builder.ToStringBuilder;
    025import org.apache.commons.lang3.builder.ToStringStyle;
    026
    027/**
    028 * <p>Helper methods for working with {@link Annotation} instances.</p>
    029 *
    030 * <p>This class contains various utility methods that make working with
    031 * annotations simpler.</p>
    032 *
    033 * <p>{@link Annotation} instances are always proxy objects; unfortunately
    034 * dynamic proxies cannot be depended upon to know how to implement certain
    035 * methods in the same manner as would be done by "natural" {@link Annotation}s.
    036 * The methods presented in this class can be used to avoid that possibility. It
    037 * is of course also possible for dynamic proxies to actually delegate their
    038 * e.g. {@link Annotation#equals(Object)}/{@link Annotation#hashCode()}/
    039 * {@link Annotation#toString()} implementations to {@link AnnotationUtils}.</p>
    040 *
    041 * <p>#ThreadSafe#</p>
    042 *
    043 * @since 3.0
    044 */
    045public class AnnotationUtils {
    046
    047    /**
    048     * A style that prints annotations as recommended.
    049     */
    050    private static final ToStringStyle TO_STRING_STYLE = new ToStringStyle() {
    051        /** Serialization version */
    052        private static final long serialVersionUID = 1L;
    053
    054        {
    055            setDefaultFullDetail(true);
    056            setArrayContentDetail(true);
    057            setUseClassName(true);
    058            setUseShortClassName(true);
    059            setUseIdentityHashCode(false);
    060            setContentStart("(");
    061            setContentEnd(")");
    062            setFieldSeparator(", ");
    063            setArrayStart("[");
    064            setArrayEnd("]");
    065        }
    066
    067        /**
    068         * {@inheritDoc}
    069         */
    070        @Override
    071        protected String getShortClassName(final Class<?> cls) {
    072            for (final Class<?> iface : ClassUtils.getAllInterfaces(cls)) {
    073                if (Annotation.class.isAssignableFrom(iface)) {
    074                    return "@" + iface.getName();
    075                }
    076            }
    077            return StringUtils.EMPTY;
    078        }
    079
    080        /**
    081         * {@inheritDoc}
    082         */
    083        @Override
    084        protected void appendDetail(final StringBuffer buffer, final String fieldName, Object value) {
    085            if (value instanceof Annotation) {
    086                value = AnnotationUtils.toString((Annotation) value);
    087            }
    088            super.appendDetail(buffer, fieldName, value);
    089        }
    090
    091    };
    092
    093    /**
    094     * <p>{@code AnnotationUtils} instances should NOT be constructed in
    095     * standard programming. Instead, the class should be used statically.</p>
    096     *
    097     * <p>This constructor is public to permit tools that require a JavaBean
    098     * instance to operate.</p>
    099     */
    100    public AnnotationUtils() {
    101    }
    102
    103    //-----------------------------------------------------------------------
    104    /**
    105     * <p>Checks if two annotations are equal using the criteria for equality
    106     * presented in the {@link Annotation#equals(Object)} API docs.</p>
    107     *
    108     * @param a1 the first Annotation to compare, {@code null} returns
    109     * {@code false} unless both are {@code null}
    110     * @param a2 the second Annotation to compare, {@code null} returns
    111     * {@code false} unless both are {@code null}
    112     * @return {@code true} if the two annotations are {@code equal} or both
    113     * {@code null}
    114     */
    115    public static boolean equals(final Annotation a1, final Annotation a2) {
    116        if (a1 == a2) {
    117            return true;
    118        }
    119        if (a1 == null || a2 == null) {
    120            return false;
    121        }
    122        final Class<? extends Annotation> type1 = a1.annotationType();
    123        final Class<? extends Annotation> type2 = a2.annotationType();
    124        Validate.notNull(type1, "Annotation %s with null annotationType()", a1);
    125        Validate.notNull(type2, "Annotation %s with null annotationType()", a2);
    126        if (!type1.equals(type2)) {
    127            return false;
    128        }
    129        try {
    130            for (final Method m : type1.getDeclaredMethods()) {
    131                if (m.getParameterTypes().length == 0
    132                        && isValidAnnotationMemberType(m.getReturnType())) {
    133                    final Object v1 = m.invoke(a1);
    134                    final Object v2 = m.invoke(a2);
    135                    if (!memberEquals(m.getReturnType(), v1, v2)) {
    136                        return false;
    137                    }
    138                }
    139            }
    140        } catch (final IllegalAccessException | InvocationTargetException ex) {
    141            return false;
    142        }
    143        return true;
    144    }
    145
    146    /**
    147     * <p>Generate a hash code for the given annotation using the algorithm
    148     * presented in the {@link Annotation#hashCode()} API docs.</p>
    149     *
    150     * @param a the Annotation for a hash code calculation is desired, not
    151     * {@code null}
    152     * @return the calculated hash code
    153     * @throws RuntimeException if an {@code Exception} is encountered during
    154     * annotation member access
    155     * @throws IllegalStateException if an annotation method invocation returns
    156     * {@code null}
    157     */
    158    public static int hashCode(final Annotation a) {
    159        int result = 0;
    160        final Class<? extends Annotation> type = a.annotationType();
    161        for (final Method m : type.getDeclaredMethods()) {
    162            try {
    163                final Object value = m.invoke(a);
    164                if (value == null) {
    165                    throw new IllegalStateException(
    166                            String.format("Annotation method %s returned null", m));
    167                }
    168                result += hashMember(m.getName(), value);
    169            } catch (final RuntimeException ex) {
    170                throw ex;
    171            } catch (final Exception ex) {
    172                throw new RuntimeException(ex);
    173            }
    174        }
    175        return result;
    176    }
    177
    178    /**
    179     * <p>Generate a string representation of an Annotation, as suggested by
    180     * {@link Annotation#toString()}.</p>
    181     *
    182     * @param a the annotation of which a string representation is desired
    183     * @return the standard string representation of an annotation, not
    184     * {@code null}
    185     */
    186    public static String toString(final Annotation a) {
    187        final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
    188        for (final Method m : a.annotationType().getDeclaredMethods()) {
    189            if (m.getParameterTypes().length > 0) {
    190                continue; //wtf?
    191            }
    192            try {
    193                builder.append(m.getName(), m.invoke(a));
    194            } catch (final RuntimeException ex) {
    195                throw ex;
    196            } catch (final Exception ex) {
    197                throw new RuntimeException(ex);
    198            }
    199        }
    200        return builder.build();
    201    }
    202
    203    /**
    204     * <p>Checks if the specified type is permitted as an annotation member.</p>
    205     *
    206     * <p>The Java language specification only permits certain types to be used
    207     * in annotations. These include {@link String}, {@link Class}, primitive
    208     * types, {@link Annotation}, {@link Enum}, and single-dimensional arrays of
    209     * these types.</p>
    210     *
    211     * @param type the type to check, {@code null}
    212     * @return {@code true} if the type is a valid type to use in an annotation
    213     */
    214    public static boolean isValidAnnotationMemberType(Class<?> type) {
    215        if (type == null) {
    216            return false;
    217        }
    218        if (type.isArray()) {
    219            type = type.getComponentType();
    220        }
    221        return type.isPrimitive() || type.isEnum() || type.isAnnotation()
    222                || String.class.equals(type) || Class.class.equals(type);
    223    }
    224
    225    //besides modularity, this has the advantage of autoboxing primitives:
    226    /**
    227     * Helper method for generating a hash code for a member of an annotation.
    228     *
    229     * @param name the name of the member
    230     * @param value the value of the member
    231     * @return a hash code for this member
    232     */
    233    private static int hashMember(final String name, final Object value) {
    234        final int part1 = name.hashCode() * 127;
    235        if (value.getClass().isArray()) {
    236            return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value);
    237        }
    238        if (value instanceof Annotation) {
    239            return part1 ^ hashCode((Annotation) value);
    240        }
    241        return part1 ^ value.hashCode();
    242    }
    243
    244    /**
    245     * Helper method for checking whether two objects of the given type are
    246     * equal. This method is used to compare the parameters of two annotation
    247     * instances.
    248     *
    249     * @param type the type of the objects to be compared
    250     * @param o1 the first object
    251     * @param o2 the second object
    252     * @return a flag whether these objects are equal
    253     */
    254    private static boolean memberEquals(final Class<?> type, final Object o1, final Object o2) {
    255        if (o1 == o2) {
    256            return true;
    257        }
    258        if (o1 == null || o2 == null) {
    259            return false;
    260        }
    261        if (type.isArray()) {
    262            return arrayMemberEquals(type.getComponentType(), o1, o2);
    263        }
    264        if (type.isAnnotation()) {
    265            return equals((Annotation) o1, (Annotation) o2);
    266        }
    267        return o1.equals(o2);
    268    }
    269
    270    /**
    271     * Helper method for comparing two objects of an array type.
    272     *
    273     * @param componentType the component type of the array
    274     * @param o1 the first object
    275     * @param o2 the second object
    276     * @return a flag whether these objects are equal
    277     */
    278    private static boolean arrayMemberEquals(final Class<?> componentType, final Object o1, final Object o2) {
    279        if (componentType.isAnnotation()) {
    280            return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2);
    281        }
    282        if (componentType.equals(Byte.TYPE)) {
    283            return Arrays.equals((byte[]) o1, (byte[]) o2);
    284        }
    285        if (componentType.equals(Short.TYPE)) {
    286            return Arrays.equals((short[]) o1, (short[]) o2);
    287        }
    288        if (componentType.equals(Integer.TYPE)) {
    289            return Arrays.equals((int[]) o1, (int[]) o2);
    290        }
    291        if (componentType.equals(Character.TYPE)) {
    292            return Arrays.equals((char[]) o1, (char[]) o2);
    293        }
    294        if (componentType.equals(Long.TYPE)) {
    295            return Arrays.equals((long[]) o1, (long[]) o2);
    296        }
    297        if (componentType.equals(Float.TYPE)) {
    298            return Arrays.equals((float[]) o1, (float[]) o2);
    299        }
    300        if (componentType.equals(Double.TYPE)) {
    301            return Arrays.equals((double[]) o1, (double[]) o2);
    302        }
    303        if (componentType.equals(Boolean.TYPE)) {
    304            return Arrays.equals((boolean[]) o1, (boolean[]) o2);
    305        }
    306        return Arrays.equals((Object[]) o1, (Object[]) o2);
    307    }
    308
    309    /**
    310     * Helper method for comparing two arrays of annotations.
    311     *
    312     * @param a1 the first array
    313     * @param a2 the second array
    314     * @return a flag whether these arrays are equal
    315     */
    316    private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) {
    317        if (a1.length != a2.length) {
    318            return false;
    319        }
    320        for (int i = 0; i < a1.length; i++) {
    321            if (!equals(a1[i], a2[i])) {
    322                return false;
    323            }
    324        }
    325        return true;
    326    }
    327
    328    /**
    329     * Helper method for generating a hash code for an array.
    330     *
    331     * @param componentType the component type of the array
    332     * @param o the array
    333     * @return a hash code for the specified array
    334     */
    335    private static int arrayMemberHash(final Class<?> componentType, final Object o) {
    336        if (componentType.equals(Byte.TYPE)) {
    337            return Arrays.hashCode((byte[]) o);
    338        }
    339        if (componentType.equals(Short.TYPE)) {
    340            return Arrays.hashCode((short[]) o);
    341        }
    342        if (componentType.equals(Integer.TYPE)) {
    343            return Arrays.hashCode((int[]) o);
    344        }
    345        if (componentType.equals(Character.TYPE)) {
    346            return Arrays.hashCode((char[]) o);
    347        }
    348        if (componentType.equals(Long.TYPE)) {
    349            return Arrays.hashCode((long[]) o);
    350        }
    351        if (componentType.equals(Float.TYPE)) {
    352            return Arrays.hashCode((float[]) o);
    353        }
    354        if (componentType.equals(Double.TYPE)) {
    355            return Arrays.hashCode((double[]) o);
    356        }
    357        if (componentType.equals(Boolean.TYPE)) {
    358            return Arrays.hashCode((boolean[]) o);
    359        }
    360        return Arrays.hashCode((Object[]) o);
    361    }
    362}