When declaring a class or an interface as being parameterizable, or when a subclass extends that parameterizable class, we come into cases where we need to access the information of those generic parameters, this is where Java Reflection comes in handy.
This tutorial will introduce ReflectionUtil, a utility class that uses java.lang.reflect standard library. It provides easy access to the standard reflect methods that are needed usually when dealing with generic object types (java.reflect.Type).

This article assumes you have some good knowledge of reflection API and the common uses of it. If not, you might find Oracle’s Reflection API Tutorial a helpful start.
ReflectionUtil covers the next functionalities:
1. Get Class object by Type
2. Create instance by Type
3. Get Types of a parameterized generic object
4. Check if a Class has a default constructor
5. Get Class object representing the type of a Field in a class
6. Get Class object representing the return type of a Method in a class
7. Get Enum constant of an enum Class by String identifier
8. Download ReflectionUtil class

1. Get Class object by Type

private static final String TYPE_NAME_PREFIX = "class ";

public static String getClassName(Type type) {
    if (type==null) {
        return "";
    }
    String className = type.toString();
    if (className.startsWith(TYPE_NAME_PREFIX)) {
        className = className.substring(TYPE_NAME_PREFIX.length());
    }
    return className;
}

public static Class<?> getClass(Type type) 
			throws ClassNotFoundException {
    String className = getClassName(type);
    if (className==null || className.isEmpty()) {
        return null;
    }
    return Class.forName(className);
}

Method ReflectionUtil#getClass(Type) is used to get java.lang.Class object from java.lang.reflect.Type. This method takes advantage of the toString() value from a Type which gives the fully qualified name of a class as "class some.package.Foo".
ReflectionUtil#getClassName(Type) substrings this last value removing the prefix "class " (with the space) to make it eligible for ReflectionUtil#getClass(Type) that in its turn uses Class.forName(String) to load the desired class properly.

2. Create instance by Type

public static Object newInstance(Type type) 
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class<?> clazz = getClass(type);
    if (clazz==null) {
        return null;
    }
    return clazz.newInstance();
}

Method ReflectionUtil#newInstance(Type type) creates a newly allocated instance of the class represented by the invoked Type object. The given Type should not represents an abstract class, an interface, an array class, a primitive type, or void, otherwise an InstantiationException is thrown.

3. Get Types of a parameterized generic object

Let's say we have the next objects:

public abstract class Foo<T> {
    //content
}

public class FooChild extends Foo<Bar> {
    //content
} 

What if we needed Class<T> object inside Foo?
This can be solved in either two ways:
- The common way of forcing FooChild to pass its own Class as next:

public abstract class Foo<T> {
    private Class<T> tClass;    

    public Foo(Class<T> tClass) {
        this.tClass = tClass;
    }
    //content
}

public class FooChild extends Foo<Bar> {
    public FooChild() {
        super(FooChild.class);
    }
    //content
} 

- Or using reflection:

public static Type[] getParameterizedTypes(Object object) {
    Type superclassType = object.getClass().getGenericSuperclass();
    if (!ParameterizedType.class.isAssignableFrom(superclassType.getClass())) {
        return null;
    }
    return ((ParameterizedType)superclassType).getActualTypeArguments();
}

Method ReflectionUtil#getParameterizedTypes(Object) returns an array of Type[] objects representing the actual type arguments to this object, which is the Type of T at runtime as in our example.
So in order for Foo to get Class<T>, it will be using ReflectionUtil#getParameterizedTypes accompanied with ReflectionUtil#getClass as next:

...
Type[] parameterizedTypes = ReflectionUtil.getParameterizedTypes(this);
Class<T> clazz = (Class<T>)ReflectionUtil.getClass(parameterizedTypes[0]);
...

You should also note this from the java.lang.reflect.ParameterizedType#getActualTypeArguments() documentation:

in some cases, the returned array can be empty. This can occur
if this type represents a non-parameterized type nested within
a parameterized type.

4. Check if a Class has a default constructor

public static boolean hasDefaultConstructor(Class<?> clazz) throws SecurityException {
    Class<?>[] empty = {};
    try {
        clazz.getConstructor(empty);
    } catch (NoSuchMethodException e) {
        return false;
    }
    return true;
}

Method ReflectionUtil#hasDefaultConstructor checks whether a java.lang.reflect.Constructor object with no parameter types is specified by the invoked Class object or not.

5. Get Class object representing the type of a Field in a class

public static Class<?> getFieldClass(Class<?> clazz, String name) {
    if (clazz==null || name==null || name.isEmpty()) {
        return null;
    }
    name = name.toLowerCase();
    Class<?> propertyClass = null;
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.getName().equals(name)) {
            propertyClass = field.getType();
            break;
        }
    }
    return propertyClass;
}

In some cases you'll be needing to get the Class object type of a declared field inside a given class knowing only the Class object containing the field, and the field's String name.
Method ReflectionUtil#getFieldClass(Class<?>, String) loops through Class#getDeclaredFields() comparing each java.lang.reflect.Field#getName() with the invoked name, when a match is found, Field#getType() is returned with the Class object needed which represents the type of our field.

6. Get Class object representing the return type of a Method in a class

public static Class<?> getMethodReturnType(Class<?> clazz, String name) {
    if (clazz==null || name==null || name.isEmpty()) {
        return null;
    }	

    name = name.toLowerCase();
    Class<?> returnType = null;
		
    for (Method method : clazz.getDeclaredMethods()) {
        if (method.getName().equals(name)) {
            returnType = method.getReturnType();
            break;
        }
    }
		
    return returnType;
}

When you need to know the return type Class object of a declared method inside a given class knowing only the Class object containing the method, and the method's String name.
Method ReflectionUtil#getMethodReturnType(Class<?>, String) loops through Class#getDeclaredMethods() comparing each java.lang.reflect.Method#getName() with the invoked name, when a match is found, Method#getReturnType() is returned with the Class object needed which represents the return type of our method.

7. Get Enum constant of an enum Class by String identifier

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getEnumConstant(Class<?> clazz, String name) {
    if (clazz==null || name==null || name.isEmpty()) {
        return null;
    }
    return Enum.valueOf((Class<Enum>)clazz, name);
}

Method ReflectionUtil#getEnumConstant(Class<?>, String) extracts the enum constant of the specified enum class with the specified name. The name must match exactly an identifier used to declare an enum constant in the given class.
This is useful when your representing enum Class<?> is of a generic type.

8. Download ReflectionUtil class

Get the full and documented ReflectionUtil.java and comment out to tell me of any improvements or add ups to this utility.

Copyrights Notice: You can freely use class ReflectionUtil.java or any code of this tutorial in your application or modify it to your needs, just keeping my name and the link would be fair.