View Javadoc

1   package net.sf.collections15.internal;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   
6   /***
7    * <code>ReflectionUtils</code> provides common methods relating to reflection,
8    * for use by other classes in Collections15.
9    * <p/>
10   * <b>This class is not indended to form part of the Collections15 public API.
11   * It's methods are subject to change at any time, and should not be invoked by
12   * code outside of the Commons15 project.
13   */
14  public class ReflectionUtils
15  {
16      /***
17       * Determines whether or not the specified object can be assigned to a
18       * reference of the specified type. </p> This method provides special
19       * handling of the primitive classes, allowing <code>Class</code>/<code>Object</code>
20       * pairs that are specified as arguments to code that involves reflection to
21       * be checked for compatibility.
22       *
23       * @param type  The type - must not be <code>null</code>, though this is not
24       *              checked.
25       * @param value The object.
26       *
27       * @return <code>true</code> if the <code>value</code> can be assigned to
28       *         reference of type <code>type</code>. If the <code>type</code>
29       *         represents a primitive java type, it is substituted with the
30       *         <code>Class</code> that represents its corresponding
31       *         non-primitive type. This method then defers to
32       *         <code>type.isInstance(value)</code>.
33       *         <p/>
34       *         Note, if <code>value</code> is <code>null</code>, this method
35       *         will always return <code>true</code>.
36       */
37      public static boolean isAssignableTo(Class type, Object value)
38      {
39          if (value == null) {
40              return true;
41          }
42          if (type.isPrimitive()) {
43              type = typeLookup.get(type);
44          }
45          return type.isInstance(value);
46      }
47  
48      private static Map<Class, Class> typeLookup;
49  
50      static
51      {
52          typeLookup = new HashMap<Class, Class>(12, 0.75f);
53          typeLookup.put(Void.TYPE, Void.class);
54          typeLookup.put(Boolean.TYPE, Boolean.class);
55          typeLookup.put(Byte.TYPE, Byte.class);
56          typeLookup.put(Short.TYPE, Short.class);
57          typeLookup.put(Character.TYPE, Character.class);
58          typeLookup.put(Integer.TYPE, Integer.class);
59          typeLookup.put(Long.TYPE, Long.class);
60          typeLookup.put(Float.TYPE, Float.class);
61          typeLookup.put(Double.TYPE, Double.class);
62      }
63  }