Showing posts with label reflection. Show all posts
Showing posts with label reflection. Show all posts

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

Tuesday, 12 July 2022

How to check whether a method exists in a Java class or not?

Using Class.getMethod(), we can check whether a method with given name exists or not.

 

public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

Return a Method object, if the method with given name and respective parameters exists, else it throws NoSuchMethodException.

 


Below snippet return true, if the method name exists with respective arguments, else false.

public static boolean isMethodExist(Class clazz, String methodName, Class<?>... parameterTypes) {

	try {
		clazz.getMethod(methodName, parameterTypes);
	} catch (NoSuchMethodException e) {
		return false;
	}
	return true;
}

 

If you are not sure about the method arguments and interested only in method name, you can use getDeclaredMethods method. Class.getDeclaredMethods return all the methods declared in this class.

 

Below snippet return true, if the method with given name exists, else false.

public static boolean isMethodExist(Class clazz, String methodName) {
	try {

		Method[] declaredMethods = clazz.getDeclaredMethods();

		for (Method method : declaredMethods) {
			if (method.getName().equals(methodName)) {
				return true;
			}
		}

	} catch (Exception e) {
		e.printStackTrace();
	}

	return false;
}

Find the below working application.

 

ArithmeticUtil.java

package com.sample.app.util;

public class ArithmeticUtil {

	public int add(int a, int b) {
		return a + b;
	}

	public int add(int a, int b, int c) {
		return a + b + c;
	}

	public int sub(int a, int b) {
		return a - b;
	}

}

ReflectionUtil.java

package com.sample.app.util;

import java.lang.reflect.Method;

public class ReflectionUtil {

	public static boolean isMethodExist(Class clazz, String methodName, Class<?>... parameterTypes) {

		try {
			clazz.getMethod(methodName, parameterTypes);
		} catch (NoSuchMethodException e) {
			return false;
		}
		return true;
	}

	public static boolean isMethodExist(Class clazz, String methodName) {
		try {

			Method[] declaredMethods = clazz.getDeclaredMethods();

			for (Method method : declaredMethods) {
				if (method.getName().equals(methodName)) {
					return true;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

}

App.java

package com.sample.app;

import com.sample.app.util.ArithmeticUtil;
import com.sample.app.util.ReflectionUtil;

public class App {
	public static void main(String[] args) {
		boolean exists = ReflectionUtil.isMethodExist(ArithmeticUtil.class, "add", int.class, int.class);
		System.out.println("Is add method with two integer arguments exists : " + exists);

		exists = ReflectionUtil.isMethodExist(ArithmeticUtil.class, "sub", int.class, int.class);
		System.out.println("Is sub method with two integer arguments exists : " + exists);

		exists = ReflectionUtil.isMethodExist(ArithmeticUtil.class, "mul", int.class, int.class);
		System.out.println("Is mul method with two integer arguments exists : " + exists);

		exists = ReflectionUtil.isMethodExist(ArithmeticUtil.class, "add");
		System.out.println("\nIs add method exists : " + exists);

		exists = ReflectionUtil.isMethodExist(ArithmeticUtil.class, "sub");
		System.out.println("Is sub method exists : " + exists);

		exists = ReflectionUtil.isMethodExist(ArithmeticUtil.class, "mul");
		System.out.println("Is mul method exists : " + exists);
	}
}

Output

Is add method with two integer arguments exists : true
Is sub method with two integer arguments exists : true
Is mul method with two integer arguments exists : false

Is add method exists : true
Is sub method exists : true
Is mul method exists : false



 

Previous                                                 Next                                                 Home

Friday, 18 March 2022

Check whether a field is annotated with given annotation or not

Using 'isAnnotationPresent' method of Field object, we can check whether an annotation for the specified type is present on this element or not.

 

Signature

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)

 

Example

field.isAnnotationPresent(Deprecated.class)

 Above snippet return true, if the field is annotated with @Deprecated, else false.

 

 


Find the below working application.

 

ChatServer.java

package com.sample.app;

public class ChatServer {

	@Deprecated
	private int connectionTimeout;
	private int bufferSize;

	public ChatServer(int connectionTimeout, int bufferSize) {
		this.connectionTimeout = connectionTimeout;
		this.bufferSize = bufferSize;
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

}

FieldAnnotationCheck.java

package com.sample.app;

import java.lang.reflect.Field;

public class FieldAnnotationCheck {
	
	public static void main(String[] args) {
		ChatServer chatServer = new ChatServer(10000, 25000);
		
		Field[] fields = chatServer.getClass().getDeclaredFields();
		for(Field field: fields) {
			if(field.isAnnotationPresent(Deprecated.class)) {
				System.out.println(field.getName() + " is depreacted");
			}
		}
		
	}

}

Output

connectionTimeout is deprecated







 

Previous                                                    Next                                                    Home

Tuesday, 2 November 2021

Java: Get all the fields and inherited fields of a class

In this post, I am going to explain how to get all the fields and inherited fields of a class.

 

Step 1: Get all the fields of current class using 'getDeclaredFields' method.

clazzTemp.getDeclaredFields()

Step 2: Get the super class of this class and repeat step 1 for this parent class. Do the steps 1 and 2 until the parent class is null.

 

clazzTemp.getSuperclass()

 

Example

public static List<Field> getAllFields(Class<?> clazz) {
	List<Field> fields = new ArrayList<Field>();
	Class<?> clazzTemp = clazz;

	do {
		fields.addAll(Arrays.asList(clazzTemp.getDeclaredFields()));
	} while ((clazzTemp = clazzTemp.getSuperclass()) != null);

	return fields;
}

Find the below working application.

 

AllFieldsOfAClass.java

package com.sample.app.fields;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AllFieldsOfAClass {

	public static class Parent {
		int parentA, parentB;
	}

	public static class Child extends Parent {
		private int childA, childB;
	}

	public static List<Field> getAllFields(Class<?> clazz) {
		List<Field> fields = new ArrayList<Field>();
		Class<?> clazzTemp = clazz;

		do {
			fields.addAll(Arrays.asList(clazzTemp.getDeclaredFields()));
		} while ((clazzTemp = clazzTemp.getSuperclass()) != null);

		return fields;
	}

	public static void main(String args[]) {

		getAllFields(Child.class).stream().forEach(field -> {
			System.out.println(field.getName());
		});
	}
}


Output

childA
childB
parentA
parent





 

 

Previous                                                    Next                                                    Home