Thursday 14 July 2022

How to get the generic arguments of a method return type

In this post, I am going to explain how to get the generic argument of the method return type.

 

Example

public static List<User> users()

 

For example, in the above example, I am expecting ‘User’ as my output.

 

How to get the generic argument of the method return type?

Step 1: Get the Method instance.

Method method = UserUtil.class.getMethod("users");

Step 2: Get the method generic return type.

Type genericReturnType = method.getGenericReturnType();

'getGenericReturnType' method return a Type object that represents the formal return type of the method represented by this Method object. If the return type is a parameterized type, the Type object returned must accurately reflect the actual type arguments used in the source code.

 

Let’s check whether the returned type is ParameterizedType or not to get the generic arguments of the method return types.

if (genericReturnType instanceof ParameterizedType) {
	ParameterizedType type = (ParameterizedType) genericReturnType;
	for (Type t : type.getActualTypeArguments()) {
		System.out.println("Type parameter: " + t);
	}
} else {
	System.out.println("Not a generic type");
}

Find the below working application.

 


User.java

package com.sample.app.dto;

public class User {

}

MethodReturnTypeDemo.java

package com.sample.app;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

import com.sample.app.dto.User;

public class MthodReturnTypeDemo {

	private static class UserUtil {
		public static List<User> users() {
			return Collections.EMPTY_LIST;
		}
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException {

		Method method = UserUtil.class.getMethod("users");

		Class<?> returnType = method.getReturnType();

		Type genericReturnType = method.getGenericReturnType();

		System.out.println("returnType : " + returnType);
		System.out.println("genericReturnType : " + genericReturnType);

		if (genericReturnType instanceof ParameterizedType) {
			ParameterizedType type = (ParameterizedType) genericReturnType;
			for (Type t : type.getActualTypeArguments()) {
				System.out.println("Type parameter: " + t);
			}
		} else {
			System.out.println("Not a generic type");
		}

	}

}

Output

returnType : interface java.util.List
genericReturnType : java.util.List<com.sample.app.dto.User>
Type parameter: class com.sample.app.dto.User


  

Previous                                                 Next                                                 Home

No comments:

Post a Comment