Created
May 19, 2020 15:12
-
-
Save amaembo/76a77ceef063974213dc12257e66e6fe to your computer and use it in GitHub Desktop.
Reified generics in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice trick!