简体   繁体   中英

Casting Long to Integer throws ClassCastException

Im trying to cast a long into int, but failed. I am use in a Servlet in Google App Engine if that matters. I have did searches to post1 , post2 docs But no results From my logs. point to this line:

//fields
private int multiplyer;
private Map<String, Object> mappings;



//the method
        Echo.log.info("key: "+WinningSetMappingEnum.multiplyer.toString()
        +"  value: "
        +mappings.get(WinningSetMappingEnum.multiplyer.toString())
        +"  "
        +mappings.get(WinningSetMappingEnum.multiplyer.toString()).getClass().getName()
                    );//For logging

         multiplyer=(Integer)mappings.get(MappingEnum.multiplyer.toString());//PROBLEM

LOG:

com.wtsang02.deserlizeMapping: key: multiplyer value: 0 java.lang.Long
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

Both Long and Integer extend java.lang.Number .

How do you want to cast one class into another that is not related directly? What you can cast are the primitive values

  Integer i = (int) (myLong.longValue())

Although it would be easier to use the intValue() method in Long .

private Map<String, Object> mappings;

returns an Object. Therefore the solution is

long l = (Long) mappings.get(WinningSetMappingEnum.multiplyer
                .toString());
        multiplyer = (int) l;

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