All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.wamblee.reflection.AnnotationUtils Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2005-2010 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.wamblee.reflection;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Utlities for working with annotations.
 * 
 * @author Erik Brakkee
 * 
 */
public class AnnotationUtils {

    /**
     * Returns the accessor for a given annotation.
     * 
     * @param aClass
     *            Class to analyse.
     * @param aAnnotation
     *            Annotation that must be present.
     * @return List of accessors. Empty list is returned if no match is found.
     */
    public static List analyse(Class aClass,
        Class aAnnotation) {
        List result = new ArrayList();

        List fields = ReflectionUtils.getAllFields(aClass);
        for (Field field : fields) {
            if (field.isAnnotationPresent(aAnnotation)) {
                result.add(new FieldAccessor(field));
            }
        }
        List methods = ReflectionUtils.getAllMethods(aClass,
            Object.class);
        for (Method method : methods) {
            if (method.isAnnotationPresent(aAnnotation)) {
                String setterName = null;
                if (method.getName().startsWith("get")) {
                    setterName = method.getName().replaceFirst("get", "set");
                } else if (method.getName().startsWith("is")) {
                    setterName = method.getName().replaceFirst("is", "set");
                }
                try {
                    Class returnType = method.getReturnType();
                    Method setter = method.getDeclaringClass()
                        .getDeclaredMethod(setterName, returnType);
                    result.add(new PropertyAccessor(method, setter));
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException("Error obtaining setter for " +
                        method.getName() + " in class " + aClass.getName(), e);
                }
            }
        }
        return result;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy