Merge pull request #9336 from alimate/BAEL-4054

BAEL-4054: Super Type Token
This commit is contained in:
rpvilao 2020-05-25 17:27:36 +02:00 committed by GitHub
commit cbe5207db2
2 changed files with 42 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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());
}
}