View Javadoc

1   // $Id: MapUtils.java,v 1.1 2004/03/27 12:29:30 powerpete Exp $
2   // [JMP, 10.03.2004] Created this file.
3   package com.pnpconsult.zeiterfassung.util;
4   
5   import java.util.Collection;
6   import java.util.Map;
7   
8   /***
9    * @author <a href="mailto:powerpete@users.sf.net">M. Petersen</a>
10   * @version $Id: MapUtils.java,v 1.1 2004/03/27 12:29:30 powerpete Exp $
11   */
12  public class MapUtils
13  {
14      private MapUtils()
15      {}
16  
17      /***
18       * Puts the value into a {@link Collection} identified by <tt>key</tt>.
19       * If the <tt>key</tt> contains no value, a new {@link Collection} is 
20       * created, using the given <tt>clazz</tt>.
21       * 
22       * @param map       The {@link Map}, to put the value into.
23       * @param key       The key, to get the {@link Collection}.
24       * @param value     The value, to put into the {@link Collection}.
25       * @param clazz     The {@link Class} of the {@link Collection} if it does
26       *                  not exist yet.
27       * 
28       * @throws IllegalArgumentException If an error occurs, such as:
29       * <ul>
30       * <li> The given {@link Class} is not a {@link Collection}.
31       * <li> The given {@link Class} is not accessible.
32       * <li> The map already contains a value for the given <tt>key</tt>, which
33       *      is no {@link Collection}.
34       * </ul>
35       */
36      public static void putMulti(Map map, Object key, Object value, Class clazz)
37      {
38          Collection c =
39              castToCollection(
40                  map.get(key),
41                  "Map contains value for key '" + key + "'");
42          if (c == null)
43          {
44              try
45              {
46                  c = castToCollection(clazz.newInstance(), "Invalid class");
47              }
48              catch (InstantiationException e)
49              {
50                  throw new IllegalArgumentException(
51                      "Unable to instantiate " + clazz);
52              }
53              catch (IllegalAccessException e)
54              {
55                  throw new IllegalArgumentException("Unable to access " + clazz);
56              }
57              map.put(key, c);
58          }
59          c.add(value);
60      }
61  
62      private static Collection castToCollection(Object o, String msg)
63      {
64          if (o == null)
65          {
66              return null;
67          }
68          if (!(o instanceof Collection))
69          {
70              throw new IllegalArgumentException(
71                  msg + ": " + o.getClass() + " is no collection.");
72          }
73          return (Collection) o;
74      }
75  }