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

io.gsonfire.gson.FieldInspector Maven / Gradle / Ivy

Go to download

A java library that adds some very useful features to Gson, like Date serializing to unix timestamp or RFC3339, method (getter) serialization, pre and post processors and many more. Check out the documentation to learn how to use it!

There is a newer version: 1.9.0
Show newest version
package io.gsonfire.gson;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @autor: julio
 */
public class FieldInspector {
    private static final Map, Field[]>> cache = new ConcurrentHashMap, Field[]>>();

    public Field[] getAnnotatedFields(Class clazz, Class annotation){
        Field[] fields = getFromCache(clazz, annotation);
        if(fields != null){
            return fields;
        }

        //We only synchronize on a cache miss, to avoid having
        //to synchronize after the cache has been built
        synchronized (cache){
            fields = getFromCache(clazz, annotation);
            if(fields == null){
                Set fieldList = new HashSet();

                for(Field m: clazz.getFields()){
                    if(m.isAnnotationPresent(annotation)){
                        m.setAccessible(true);
                        fieldList.add(m);
                    }
                }

                for(Field m: clazz.getDeclaredFields()){
                    if(m.isAnnotationPresent(annotation)){
                        m.setAccessible(true);
                        fieldList.add(m);
                    }
                }

                if(!cache.containsKey(clazz)){
                    cache.put(clazz, new ConcurrentHashMap, Field[]>());
                }

                fields = new Field[fieldList.size()];
                cache.get(clazz).put(annotation, fieldList.toArray(fields));
            }
        }

        return fields;
    }

    private Field[] getFromCache(Class clazz, Class annotation){
        Map, Field[]> annotationMap = cache.get(clazz);
        if(annotationMap != null){
            Field[] fields = annotationMap.get(annotation);
            if(fields != null){
                return fields;
            }
        }
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy