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

io.gsonfire.util.reflection.CachedReflectionFactory 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.util.reflection;

import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by julio on 10/1/16.
 */
public class CachedReflectionFactory implements Factory {

    private final ConcurrentMap> cache = new ConcurrentHashMap>();

    @Override
    public  T get(Class clazz) {
        SoftReference resultRef = (SoftReference) cache.get(clazz);
        if(resultRef != null) {
            T result = resultRef.get();
            if (result != null) {
                return result;
            }
        }

        //We need to create the object
        try {
            T newObject = clazz.newInstance();
            cache.putIfAbsent(clazz, new SoftReference(newObject));
            return newObject;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


}