[英]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: 我的程序有一个方法,可以获取特定行的计数并将其转换为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. 当查询结果为0时,转换工作正常。但是当查询结果为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. Java不是C ++,你不能编写自己的转换运算符。
In Java you need to use explicit functions to do what you want. 在Java中,您需要使用显式函数来执行您想要的操作。 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'. Long不是BigInteger的子类,所以'Long不是BigInteger'。 So, your Long can not be cast to a BigInteger. 所以,你的Long不能被强制转换为BigInteger。
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html
Use static method of BigInteger: BigInteger.valueOf(long val);
使用BigInteger的静态方法: BigInteger.valueOf(long val);
as BigInteger.valueOf(query.firstRow())
. 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
. 并且您的代码在零结果的情况下工作,因为您已使用BigInteger
类型的ZERO初始化count
。 So, in case of zero results, your code does not get into the if statement (no casting is tried) and returns count
straight away. 因此,如果结果为零,则代码不会进入if语句(不尝试转换)并立即返回count
。
You might also want to read about Upcasting and Downcasting in Java. 您可能还想阅读Java中的Upcasting和Downcasting。
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. java.lang.Long
和java.math.BigInteger
位于不同的层次结构中。 They cannot be castes to each other. 他们不能相互结合。 You can create new BigInteger
by using static factory method
: 您可以使用static factory method
创建新的BigInteger
:
BigInteger.valueOf(yourLong);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.