Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 43 additions & 4 deletions api/src/org/labkey/api/data/ConvertHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -791,16 +791,27 @@ else if (value instanceof Number n)
}
}

/** Simple genericized wrapper around ConvertUtils.convert(). Also handles calling toString() on value, if non-null */

/** Genericized wrapper around ConvertUtils.convert(). */
public static <T> T convert(Object value, Class<T> cl)
{
if (value == null)
{
var ret = ConvertUtils.convert(value, cl);
if (ret == null)
return null;
try
{
return cl.cast(ret);
}
catch (ClassCastException ex)
{
// for testing let's blow up dramatically here
if (cl.isPrimitive())
throw new IllegalArgumentException("primitive type is not allowed: " + cl.getName());
throw new ConversionException("Could not convert value to " + cl.getSimpleName());
}
return (T)ConvertUtils.convert(value.toString(), cl);
}


public static SimpleConvert getSimpleConvert(Class<?> targetType)
{
// ConvertUtils handling String.class and String[].class depends on the source type,
Expand Down Expand Up @@ -1060,6 +1071,34 @@ public Object convert(Class type, Object value)

public static class TestCase extends Assert
{
@Test
public void testConvertHelperEqualsConvertUtils()
{
{
// ConvertHelper used to call toString() which would break this test
var a = ConvertHelper.convert("a,b,c", String[].class);
assert a instanceof String[] arr && arr.length == 3;
var b = ConvertHelper.convert(a, String[].class);
assertArrayEquals(a, b);
}

{
var a = ConvertUtils.convert("a,b,c", String[].class);
assert a instanceof String[] arr && arr.length == 3;
var b = ConvertUtils.convert(a, String[].class);
assertArrayEquals((String [])a, (String [])b);
}

{
// ConvertHelper used to short-circuit null which would break this test
var a = ConvertUtils.convert((String)null, MultiChoice.Array.class);
var b = ConvertHelper.convert(null, MultiChoice.Array.class);
assertNotNull(a);
assertEquals(a,b);
}
}


@Test
public void testConvertTimestamp()
{
Expand Down