Author: julien(a)jboss.com
Date: 2008-03-20 10:20:47 -0400 (Thu, 20 Mar 2008)
New Revision: 10349
Modified:
modules/common/trunk/common/src/main/java/org/jboss/portal/common/reflect/Reflection.java
modules/common/trunk/common/src/test/java/org/jboss/portal/test/common/reflect/ReflectionTestCase.java
Log:
added a safe cast util method
Modified:
modules/common/trunk/common/src/main/java/org/jboss/portal/common/reflect/Reflection.java
===================================================================
---
modules/common/trunk/common/src/main/java/org/jboss/portal/common/reflect/Reflection.java 2008-03-20
03:52:18 UTC (rev 10348)
+++
modules/common/trunk/common/src/main/java/org/jboss/portal/common/reflect/Reflection.java 2008-03-20
14:20:47 UTC (rev 10349)
@@ -139,4 +139,30 @@
return null;
}
+ /**
+ * Attempt to cast the value argument to the provided type argument. If the value
argument type is assignable
+ * to the provided type, the value is returned, otherwise if it is not or the value is
null, null is returned.
+ *
+ * @param value the value to cast
+ * @param type the type to downcast
+ * @return the casted value or null
+ */
+ public static <T> T safeCast(Object value, Class<T> type)
+ {
+ if (value == null)
+ {
+ return null;
+ }
+ else
+ {
+ if (type.isAssignableFrom(value.getClass()))
+ {
+ return type.cast(value);
+ }
+ else
+ {
+ return null;
+ }
+ }
+ }
}
Modified:
modules/common/trunk/common/src/test/java/org/jboss/portal/test/common/reflect/ReflectionTestCase.java
===================================================================
---
modules/common/trunk/common/src/test/java/org/jboss/portal/test/common/reflect/ReflectionTestCase.java 2008-03-20
03:52:18 UTC (rev 10348)
+++
modules/common/trunk/common/src/test/java/org/jboss/portal/test/common/reflect/ReflectionTestCase.java 2008-03-20
14:20:47 UTC (rev 10349)
@@ -26,6 +26,9 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.AbstractList;
import org.jboss.portal.common.reflect.Reflection;
@@ -87,4 +90,18 @@
assertEquals(methodName, effectiveMethod.getName());
}
+ public void testSafeCast()
+ {
+ Integer i = 3;
+ assertSame(i, Reflection.safeCast(i, Integer.class));
+
+ //
+ assertNull(Reflection.safeCast(3L, Integer.class));
+
+ //
+ ArrayList list = new ArrayList();
+ assertSame(list, Reflection.safeCast(list, List.class));
+ assertSame(list, Reflection.safeCast(list, AbstractList.class));
+ }
+
}
Show replies by date