io.gsonfire.gson.MethodInspector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gson-fire Show documentation
Show all versions of gson-fire Show documentation
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!
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 extends Annotation> 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 extends Annotation> annotation){
Map, Method[]> annotationMap = cache.get(clazz);
if(annotationMap != null){
Method[] methods = annotationMap.get(annotation);
if(methods != null){
return methods;
}
}
return null;
}
}