简体   繁体   中英

java.lang.Long cannot be cast to java.math.BigInteger

My program has a method that fetches the count of a particular row and convert it into BigInteger:

private BigInteger getSameSatPremise(ServiceAgreement sa) {
BigInteger count = BigInteger.ZERO;

    StringBuffer queryHql = new StringBuffer();
    queryHql.append("from Table t1");
    Query query = createQuery(queryHql.toString());
    query.addResult("count", "count(distinct t1.column1)");
    if (query.listSize() > 0) {
        count = (BigInteger) query.firstRow();
    }
    return count;
}

The casting works fine when the result from the query is 0. But I get a casting error like below when the result from the query is 2.

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.math.BigInteger

Can anyone help.

Java ain't C++, you can't write your own conversion operators.

In Java you need to use explicit functions to do what you want. In your case that's the considerably more verbose

BigInteger.valueOf(query.firstRow())

Long is not a subclass of BigInteger, so 'Long is NOT BigInteger'. So, your Long can not be cast to a BigInteger.

https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html

Use static method of BigInteger: BigInteger.valueOf(long val); as BigInteger.valueOf(query.firstRow()) .

And your code works in case of zero results because, you have initialized the count with a ZERO of type BigInteger . So, in case of zero results, your code does not get into the if statement (no casting is tried) and returns count straight away.

You might also want to read about Upcasting and Downcasting in Java.

What is the difference between up-casting and down-casting with respect to class variable

java.lang.Long and java.math.BigInteger are in a different hierarchies. They cannot be castes to each other. You can create new BigInteger by using static factory method :

BigInteger.valueOf(yourLong);

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