/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.massivecraft.factions.gson; import java.lang.reflect.Constructor; /** * Use the default constructor on the class to instantiate an object. * * @author Joel Leitch */ final class DefaultConstructorAllocator { private static final Constructor NULL_CONSTRUCTOR = createNullConstructor(); private final Cache, Constructor> constructorCache; public DefaultConstructorAllocator() { this(200); } public DefaultConstructorAllocator(int cacheSize) { constructorCache = new LruCache, Constructor>(cacheSize); } // for testing purpose final boolean isInCache(Class cacheKey) { return constructorCache.getElement(cacheKey) != null; } private static final Constructor createNullConstructor() { try { return getNoArgsConstructor(Null.class); } catch (Exception e) { return null; } } public T newInstance(Class c) throws Exception { Constructor constructor = findConstructor(c); return (constructor != null) ? constructor.newInstance() : null; } @SuppressWarnings("unchecked") private Constructor findConstructor(Class c) { Constructor cachedElement = (Constructor) constructorCache.getElement(c); if (cachedElement != null) { if (cachedElement == NULL_CONSTRUCTOR) { return null; } else { return cachedElement; } } Constructor noArgsConstructor = getNoArgsConstructor(c); if (noArgsConstructor != null) { constructorCache.addElement(c, noArgsConstructor); } else { constructorCache.addElement(c, NULL_CONSTRUCTOR); } return noArgsConstructor; } private static Constructor getNoArgsConstructor(Class c) { try { Constructor declaredConstructor = c.getDeclaredConstructor(); declaredConstructor.setAccessible(true); return declaredConstructor; } catch (Exception e) { return null; } } // placeholder class for Null constructor private static final class Null { } }