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(); + } + +}