Consider the following test of Java\'s ArrayList#toArray
method. Note that I borrowed the code from this helpful answer.
public class GenericTest {
ArrayStoreException
exists precisely because Java's type system cannot handle this situation properly (IIRC, by the time Generics came along, it was too late to retrofit arrays in the same manner as the collections framework).
So you can't prevent this problem in general at compile time.
You can of course create internal APIs to wrap such operations, to reduce the likelihood of accidentally getting the types wrong.
See also: