From d2ccc3159f029fa1f1618cb64c5b86be259487c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timo=20Westk=C3=A4mper?= Date: Wed, 7 Jan 2009 13:27:25 +0000 Subject: [PATCH] added reflection based FactoryMap implementation --- .../com/mysema/query/util/FactoryMap.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 querydsl-core/src/main/java/com/mysema/query/util/FactoryMap.java diff --git a/querydsl-core/src/main/java/com/mysema/query/util/FactoryMap.java b/querydsl-core/src/main/java/com/mysema/query/util/FactoryMap.java new file mode 100644 index 000000000..9a684282d --- /dev/null +++ b/querydsl-core/src/main/java/com/mysema/query/util/FactoryMap.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2006 Mysema Ltd. + * All rights reserved. + * + */ +package com.mysema.query.util; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * FactoryMap provides + * + * @author Timo Westkämper + * @version $Id: FactoryMap.java 3549 2008-06-10 17:56:47Z tiwe $ + */ +public abstract class FactoryMap{ + + private final Map,V> cache = new HashMap,V>(); + + private Method createMethod; + + public FactoryMap(){ + for (Method m : getClass().getMethods()){ + if (m.getName().equals("create")) createMethod = m; + } + if (createMethod == null){ + throw new IllegalArgumentException("No create method given"); + }else{ + createMethod.setAccessible(true); + } + } + + @SuppressWarnings("unchecked") + public final V get(Object... args){ + List key = Arrays.asList(args); + if (cache.containsKey(key)){ + return cache.get(key); + }else{ + try { + V value = (V) createMethod.invoke(this, args); + cache.put(key, value); + return value; + } catch (Exception e) { + throw new RuntimeException("error", e); + } + } + } + + public void clear(){ + cache.clear(); + } + +}