Merge pull request #9336 from alimate/BAEL-4054
BAEL-4054: Super Type Token
This commit is contained in:
commit
cbe5207db2
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.supertype;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public abstract class TypeReference<T> {
|
||||
|
||||
private final Type type;
|
||||
|
||||
public TypeReference() {
|
||||
Type superclass = getClass().getGenericSuperclass();
|
||||
type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.supertype;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TypeReferenceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenGenericToken_whenUsingSuperTypeToken_thenPreservesTheTypeInfo() {
|
||||
TypeReference<Map<String, Integer>> token = new TypeReference<Map<String, Integer>>() {};
|
||||
Type type = token.getType();
|
||||
|
||||
assertEquals("java.util.Map<java.lang.String, java.lang.Integer>", type.getTypeName());
|
||||
|
||||
Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
|
||||
assertEquals("java.lang.String", typeArguments[0].getTypeName());
|
||||
assertEquals("java.lang.Integer", typeArguments[1].getTypeName());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue