简体   繁体   中英

how to remove class cast exception in spring java?

I have written code that uses spring util namespace. I have a class named City with the following properties:

private List<String> name;
private List<String> state;
private List<Integer> population;
//setter and getter methods go here ...

and I configured the application context as:

<util:list id="cities" list-class="java.util.ArrayList">
    p:name="chennai" p:state="tamilnadu" p:population="2000000"/>
  <bean class="com.example2.City"
        p:name="bang" p:state="karnataka" p:population="3000000"/>
</util:list>

When I run the application it gives me the following error:

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.example2.City

Will someone help me out? Thanks.

I think you have a wrong City class defined. Why does a City have to have a list of names and a list of population numbers ?

I think City should look more like:

public class City {
   private String name;

   private String state;

   private String population;

   //accessors
}

In this case, the <util:list> should look like:

<util:list id="cities" list-class="java.util.ArrayList">
  <bean class="com.example2.City"
        p:name="bang" 
        p:state="karnataka" 
        p:population="3000000"/>
  <bean class="com.example2.City"
        p:name="chennai" 
        p:state="tamilnadu" 
        p:population="2000000"/>
</util:list>

and you will have a list of two cities .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM