TypeUtil

Introduction

Utility class encapsulation for java.lang.reflect.Type, the main functions include:

  1. Getting parameter types and return types (both Type and Class) of a method
  2. Obtaining generic parameter types (including generic parameters of an object or generic types of collections)

Methods

First, let’s define a class:

public class TestClass {
 public List<String> getList(){
 return new ArrayList<>();
 }
 
 public Integer intTest(Integer integer) {
 return 1;
 }
}

getClass

Gets the original class of the Type.

getParamType

Gets the generic type of a method parameter.

Example:

Method method = ReflectUtil.getMethod(TestClass.class, "intTest", Integer.class);
Type type = TypeUtil.getParamType(method, 0);
// Result: Integer.class

getReturnType

Gets the return type of a method.

Example:

Method method = ReflectUtil.getMethod(TestClass.class, "getList");
Type type = TypeUtil.getReturnType(method);
// Result: java.util.List<java.lang.String>

getTypeArgument

Gets the type argument of a generic type.

Example:

Method method = ReflectUtil.getMethod(TestClass.class, "getList");
Type type = TypeUtil.getReturnType(method);

Type type2 = TypeUtil.getTypeArgument(type);
// Result: String.class