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

se.vgregion.ldapservice.search.beanutil.MetaHelp Maven / Gradle / Ivy

The newest version!
package se.vgregion.ldapservice.search.beanutil;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;

public class MetaHelp {

    private static Map, BeanInfo> beanInfoCache = new HashMap, BeanInfo>();

    private static Map> descriptors = new HashMap>();

    public static BeanInfo getBeanInfo(Class clazz) {
        if (clazz == null) throw new IllegalArgumentException("Argument cannot be null.");
        BeanInfo result = beanInfoCache.get(clazz);
        if (result != null) return result;
        try {
            result = Introspector.getBeanInfo(clazz);
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
        beanInfoCache.put(clazz, result);

        return result;
    }

    public static Map getDescriptors(BeanInfo key) {
        Map result = descriptors.get(key);
        if (result == null) {
            result = new HashMap();
            for (PropertyDescriptor pd : key.getPropertyDescriptors()) {
                result.put(pd.getName(), pd);
            }
        }
        return result;
    }

    public static Field getField(Class clazz, String name) {
        Field result = null;
        try {
            result = clazz.getDeclaredField(name);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            if (clazz.equals(Object.class)) return null;
            return getField(clazz.getSuperclass(), name);
        }
        return result;
    }

    public static Set getFieldNamesByAnnotations(Class beanClass, Set> lookingFor) {
        Set result = new HashSet();
        for (Field field : beanClass.getDeclaredFields()) {
            for (Class annotation : lookingFor) {
                if (field.isAnnotationPresent(annotation)) {
                    result.add(field.getName());
                }
            }
        }
        return result;
    }

    public static Set getFieldNamesByAnnotations(Class beanClass, Class... lookingFor) {
        return getFieldNamesByAnnotations(beanClass, new HashSet>(Arrays.asList(lookingFor)));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy