Skip to content

harawata/typeparameterresolver

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Maven Central License GitHub CI

TypeParameterResolver: resolve actual types

The library provides convenience API on top of Java Reflection so that you can resolve actual types of fields, method parameters, and method return types.

The code is based on TypeParameterResolver from mybatis-3.

Sample

<dependency>
  <groupId>net.harawata.reflection</groupId>
  <artifactId>typeparameterresolver</artifactId>
  <version>...</version>
</dependency>
abstract class StringIntegerMap implements Map<String, Integer> {
}

@Test
void testEntry() throws NoSuchMethodException {
    Method get = StringIntegerMap.class.getMethod("get", Object.class);

    // Regular getReturnType returns Object since generic type is erased.
    assertEquals(Object.class, get.getReturnType());
    // getGenericReturnType returns type variable name, however, it does not
    // resolve to the actual type
    assertEquals("V", get.getGenericReturnType().toString());
    assertEquals("V", get.getAnnotatedReturnType().toString());

    // TypeParameterResolver comes to rescue, and it resolves the actual type
    // according to type arguments of the given class.
    Type getReturnType = TypeParameterResolver.resolveReturnType(get, StringIntegerMap.class);
    assertEquals(Integer.class, getReturnType);
}

APIs:

  • Type resolveFieldType(Field field, Type srcType)
  • Type resolveReturnType(Method method, Type srcType)
  • Type[] resolveParamTypes(Method method, Type srcType)

License

Apache-2.0

Similar projects