hibernate返回的數(shù)據(jù)類型是List<Object>的,所以我不小心把其轉(zhuǎn)換為List<Long>,結(jié)果并沒有報錯,但當(dāng)我調(diào)用 List<Long>的get方法獲取數(shù)據(jù)時報錯:類型轉(zhuǎn)換錯誤,下面來復(fù)現(xiàn)這個問題。
oracle中的類型是Number,在hibernate中對應(yīng)的其實是BigDecimal,
hibernate對BigDecimal做了類型擦除,所以Java代碼獲取到的是List<Object>的結(jié)果。
運行以下代碼模擬 hibernate返回數(shù)值類型,并進行類型轉(zhuǎn)換
import java.util.ArrayList;
import java.util.List;
import java.math.BigDecimal;
class Untitled {
public static void main(String[] args) {
System.out.println("A");
List<BigDecimal> decimals = new ArrayList<>();
decimals.add(new BigDecimal(100));
decimals.add(new BigDecimal(101));
List objs = decimals;
List<Long> lll = (List<Long> )objs;
System.out.println("B");
Long aaa = (Long)lll.get(0);
System.out.println("C");
}
}
以下為上述代碼執(zhí)行結(jié)果:
A
B
Note: /usercode/file.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Exception in thread "main" java.lang.ClassCastException: class java.math.BigDecimal cannot be cast to class java.lang.Long (java.math.BigDecimal and java.lang.Long are in module java.base of loader 'bootstrap')
at file.main(file.java:14)
好了,問題來了,為什么在執(zhí)行 List<Long> lll = (List<Long> )objs;時,代碼沒報類型轉(zhuǎn)換錯誤,反而在后面使用時Long aaa = (Long)lll.get(0);才報錯呢?
結(jié)論:
因為類型擦除,所以 :
List<Long> lll = (List<Long> )objs;等價于 List lll = (List)objs;
因此這里看似用了類型轉(zhuǎn)換,實際上什么都沒有做。
而在執(zhí)行 Long aaa = (Long)lll.get(0);時,lll.get(0)返回的Object類型對象實則是BigDecimal類型的實例,此時發(fā)現(xiàn)BigDecimal不能轉(zhuǎn)換成Long,所以報錯