You can use arrayPrimitiveType.getMaxLength(element) in the loop and you won't need to do any casting.