How can a List<Long> references to an ArrayList which has BigInteger values

ぐ巨炮叔叔 提交于 2020-05-14 10:45:29

问题


This method is defined in a JpaRepository and runs a native PostgreSQL query.

List<Long> distributorIds = distributorRepository
.findDistributorIdsWithChildren(distributorId)

It runs with no exception and on runtime I see BigInteger values in returned distributorIds ArrayList instead of Long values.

It's same with this question: Bug in Spring Data JPA: Spring Data returns List<BigInteger> instead of List<Long>

So how can this bug occur? I mean how JAVA allows this? If Java doesn't check this kind of type errors isn't it a problem with generics in JAVA.

Note: I also checked the type hierarchy for Long and BigInteger and there is no sub/super class relation.


回答1:


Generic type checks are a compile time feature. At runtime all type information is lost. See "type erasure". The behavior you see can easily happen if, for example, a legacy API that uses non-generic collections is mapped to an API that uses generics and requires a cast of the collection. If that collection happens to contain objects of an unexpected type you will, sadly, only find out at runtime.



来源:https://stackoverflow.com/questions/60948445/how-can-a-listlong-references-to-an-arraylist-which-has-biginteger-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!