Skip to content

Keeping the type at runtime

The situation

A team writes a generic repository:

```java class Repository<T> { private final List<T> items = new ArrayList<>();

void add(T item) { items.add(item); }

// Intended: return every stored item that is a Student List<Student> students() { List<Student> out = new ArrayList<>(); for (T item : items) { if (item instanceof Student) out.add((Student) item); } return out; } } ```

Elsewhere, a developer writes:

java Repository<Student> repo = new Repository<>(); List<Object> raw = (List) someMethodReturningRepositoryItems(); raw.add("not a student");

The code compiles with a warning. At runtime a ClassCastException is thrown, but not on the line that added the string.

The team wants Repository to reject wrong types at the moment they are added, even through a raw reference. What achieves that?