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

io.gsonfire.gson.MethodInspector 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.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Class reponsible for returning an array of methods that are annotated with a particular class
 * @autor: julio
 */
public class MethodInspector {

    private static final Map, Method[]>> cache = new ConcurrentHashMap, Method[]>>();

    public Method[] getAnnotatedMethods(Class clazz, Class annotation){
        Method[] methods = getFromCache(clazz, annotation);
        if(methods != null){
            return methods;
        }

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

                for(Method m: clazz.getMethods()){
                    if(m.isAnnotationPresent(annotation)){
                        methodList.add(m);
                    }
                }

                for(Method m: clazz.getDeclaredMethods()){
                    if(m.isAnnotationPresent(annotation)){
                        m.setAccessible(true);
                        methodList.add(m);
                    }
                }

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

                methods = new Method[methodList.size()];
                cache.get(clazz).put(annotation, methodList.toArray(methods));
            }
        }

        return methods;
    }

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

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy