Created
December 13, 2012 19:01
-
-
Save eribeiro/4278743 to your computer and use it in GitHub Desktop.
How to retrieve the generics type of a class (even if subclassed). DISCLAIMER: it doesn't work, but for the most simple case [1]. If you need a bit more [2] then go with 3rd party lib (like classmate). * [1] class Bar extends Foo<String> {...} * [2] class Bar extends Foo<List<String>> {...}
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
public class GenericsTest { | |
public static void main(String[] args) { | |
Bar b = new Bar("Test"); | |
System.out.println(b.getReferenceType().getType()); | |
} | |
static class TypeReference<T> { | |
private final Class<?> type; | |
public TypeReference(T t) { | |
type = t.getClass(); | |
} | |
public Class<?> getType() { | |
return type; | |
} | |
} | |
static class Foo<T> { | |
private T value; | |
private final TypeReference<T> referenceType; | |
public Foo(T value) { | |
this.value = value; | |
this.referenceType = new TypeReference<T>(value); | |
} | |
public TypeReference<T> getReferenceType() { | |
return referenceType; | |
} | |
} | |
static class Bar extends Foo<String> { | |
public Bar(String value) { | |
super(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment