Skip to content

Instantly share code, notes, and snippets.

@amaembo
Created May 19, 2020 15:12
Show Gist options
  • Save amaembo/76a77ceef063974213dc12257e66e6fe to your computer and use it in GitHub Desktop.
Save amaembo/76a77ceef063974213dc12257e66e6fe to your computer and use it in GitHub Desktop.
Reified generics in Java
import java.util.*;
@SuppressWarnings("ALL")
class Test {
static class ReifiedList<T> extends AbstractList<T> {
private final List<T> delegate = new ArrayList<>();
private final Class<?> type;
@SafeVarargs
ReifiedList(@Deprecated T... unused) {
if (unused == null || unused.length != 0) {
throw new IllegalArgumentException();
}
type = unused.getClass().getComponentType();
}
public T typeCheck(T element) {
if (!type.isInstance(element)) {
throw new IllegalArgumentException();
}
return element;
}
public boolean add(T element) { return delegate.add(typeCheck(element)); }
public T set(int index, T element) { return delegate.set(index, typeCheck(element)); }
public T get(int index) { return delegate.get(index); }
public int size() { return delegate.size(); }
public boolean equals(Object o) { return o == this || delegate.equals(o); }
public int hashCode() { return delegate.hashCode(); }
public String toString() { return delegate.toString(); }
}
public static void main(String[] args) {
List<String> list = new ReifiedList<>();
list.add("foo");
((List) list).add(1); // Exception in thread "main" java.lang.IllegalArgumentException
System.out.println(list);
}
}
@chochos
Copy link

chochos commented May 19, 2020

Nice trick!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment