- /**
- * 简单的对象创建工厂
- *
- * @author lazyp
- * @since 1.0
- */
- public final class SimpleObjectFactory {
- private static final Logger logger = Logger.getLogger(SimpleObjectFactory.class);
- private static final Lock LOCK = new ReentrantLock();
- private static final ConcurrentHashMap<String, Object> OBJ_CACHE = new ConcurrentHashMap<String, Object>(16);
-
- /**
- * 需要一个无参构造函数
- *
- * @param cls
- * @return
- */
- public static <T> T createInstance(Class<T> cls) {
- String classStr = cls.getCanonicalName();
- return createInstance(classStr);
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T createInstance(String classStr) {
- if (StringUtils.isBlank(classStr)) {
- return null;
- }
-
- logger.debug(classStr);
-
- if (OBJ_CACHE.get(classStr) != null) {
- return (T) OBJ_CACHE.get(classStr);
- }
-
- try {
- LOCK.lock();
- if (OBJ_CACHE.get(classStr) != null) {
- return (T) OBJ_CACHE.get(classStr);
- }
-
- logger.info("Create The " + classStr + " instance.");
-
- T instance = (T) Class.forName(classStr).newInstance();
- OBJ_CACHE.putIfAbsent(classStr, instance);
- return instance;
-
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- logger.error(e.getMessage());
- return null;
- } finally {
- LOCK.unlock();
- }
-
- }
-
- public static void main(String[] args) {
-
- }
- }
复制代码 |
|