java.lang.Long无法强制转换为java.math.BigInteger

时间:2016-04-06 11:32:57

标签: java hql

我的程序有一个方法可以获取特定行的计数并将其转换为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;
}

当查询结果为0时,转换工作正常。但是当查询结果为2时,我得到如下所示的转换错误。

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

任何人都可以提供帮助。

3 个答案:

答案 0 :(得分:11)

Java不是C ++,你不能编写自己的转换运算符。

在Java中,您需要使用显式函数来执行您想要的操作。在你的情况下,这是更加冗长的

BigInteger.valueOf(query.firstRow())

答案 1 :(得分:1)

Long不是BigInteger的子类,所以' Long不是BigInteger'。所以,你的Long不能被强制转换为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

使用BigInteger的静态方法:BigInteger.valueOf(long val);BigInteger.valueOf(query.firstRow())

并且您的代码在零结果的情况下有效,因为您已使用类型为count的ZERO初始化BigInteger。因此,如果结果为零,则代码不会进入if语句(不尝试强制转换)并立即返回count

您可能还想阅读有关Java中的Upcasting和Downcasting的内容。

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

答案 2 :(得分:0)

java.lang.Longjava.math.BigInteger位于不同的层次结构中。他们不能相互结合。您可以使用BigInteger

创建新的static factory method
BigInteger.valueOf(yourLong);
相关问题