Fix Class Cast Exception on some generics types

Fix Class Cast Exception on some generics types, see the test for the specific case.