[ 
https://issues.apache.org/jira/browse/LANG-1295?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15758385#comment-15758385
 ] 

Duncan Jones commented on LANG-1295:
------------------------------------

The only solution I can think of here is to deprecate the original method and 
instead offer:

{code:java}
    @SafeVarargs
    public static <T> T[] toArrayOf(Class<T> clazz, final T... items) {
        if (items == null) {
            return null;
        }
        
        @SuppressWarnings("unchecked")
        T[] result = (T[]) Array.newInstance(clazz, items.length);
        
        System.arraycopy(items, 0, result, 0, items.length);
        return result;
    }
{code}

I believe this new method is safe, since it only relies on the items being of 
type {{T}}, but doesn't care whether {{items}} is a {{T[]}}.

Thoughts and comments on this issue very welcome!

> ArrayUtils.toArray(T... items) has unsafe use of varargs
> --------------------------------------------------------
>
>                 Key: LANG-1295
>                 URL: https://issues.apache.org/jira/browse/LANG-1295
>             Project: Commons Lang
>          Issue Type: Bug
>          Components: lang.*
>    Affects Versions: 3.5
>            Reporter: Duncan Jones
>            Priority: Critical
>
> {{ArrayUtils.toArray(T... items)}} is marked as {{@SafeVarargs}}, but I 
> suspect the use of the varargs is unsafe.
> An example, drawn heavily from [this StackOverflow 
> answer|http://stackoverflow.com/a/14252221/474189], demonstrates this:
> {code:java}
> static <T> T[] arrayOfTwo(T a, T b) {
>     return ArrayUtils.toArray(a, b);
> }
> @Test
> public void testBadVarArgs() throws Exception {
>     @SuppressWarnings("unused") // Need to assign to trigger exception
>     String[] result = arrayOfTwo("foo", "bar");
> }
> {code}
> the above code throws an exception: {{java.lang.ClassCastException: 
> [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;}}.



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)

Reply via email to