问题
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