manoj
manoj

Reputation: 21

java.lang.reflect.InvocationTargetException in Java

if(locs!=null)
{
    System.out.println("location are not null");
    Iterator ite = locs.iterator();
    DefaultComboItem locObj = null;
    ArrayList locCode = null;
    String cod=null;
    String name=null;
    while(ite.hasNext())
    {
        locCode = (ArrayList) ite.next();
        Iterator iter = locCode.iterator();
        while(iter.hasNext())
        {
            cod=(String)iter.next();
            System.out.println("Code="+cod);
            name=(String)iter.next();
            System.out.println("name="+name);
            locObj = new DefaultComboItem(cod, name);
            colRet.add(locObj);
        }
    }

}

on executing above code i am getting "java.lang.reflect.InvocationTargetException" getting this exception on cod=(String)iter.next(); line, because iter.next(); returns bigDecimal value and i am converting into String variable

Please help me

Upvotes: 0

Views: 3953

Answers (2)

Andrei Fierbinteanu
Andrei Fierbinteanu

Reputation: 7826

You can't cast a BigDecimal directly to String. Try iter.next().toString() instead.

Also it would be a good idea to use generics on the Iterators since it makes it clearer what they return (and you can access the specific methods of that class directly (no cast needed)).

Upvotes: 2

Edward Dale
Edward Dale

Reputation: 30133

You're calling next() twice, but only checking hasNext() once in the while loop condition. If your list has an odd number of elements, this code will throw a NoSuchElementException, which may be getting wrapped in an InvocationTargetException somewhere.

Upvotes: 3

Related Questions