diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java new file mode 100644 index 0000000000..2021f42239 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java @@ -0,0 +1,18 @@ +package com.baeldung.supertype; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public abstract class TypeReference { + + private final Type type; + + public TypeReference() { + Type superclass = getClass().getGenericSuperclass(); + type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java new file mode 100644 index 0000000000..24e3b698e2 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java @@ -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> token = new TypeReference>() {}; + Type type = token.getType(); + + assertEquals("java.util.Map", type.getTypeName()); + + Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments(); + assertEquals("java.lang.String", typeArguments[0].getTypeName()); + assertEquals("java.lang.Integer", typeArguments[1].getTypeName()); + } +}