Get the class represented by the reflected type. - Java Reflection

Java examples for Reflection:Field Get

Description

Get the class represented by the reflected type.

Demo Code

// Copyright 2008, 2010 The Apache Software Foundation
//package com.java2s;
import java.lang.reflect.*;

public class Main {
    /**/*from  ww w  .  ja v a  2s.  c o  m*/
     * Get the class represented by the reflected type.
     * This method is lossy; You cannot recover the type information from the class that is returned.
     * <p/>
     * {@code TypeVariable} the first bound is returned. If your type variable extends multiple interfaces that information
     * is lost.
     * <p/>
     * {@code WildcardType} the first lower bound is returned. If the wildcard is defined with upper bounds
     * then {@code Object} is returned.
     *
     * @param actualType
     *           a Class, ParameterizedType, GenericArrayType
     * @return the un-parameterized class associated with the type.
     */
    public static Class asClass(Type actualType) {
        if (actualType instanceof Class)
            return (Class) actualType;

        if (actualType instanceof ParameterizedType) {
            final Type rawType = ((ParameterizedType) actualType)
                    .getRawType();
            // The sun implementation returns getRawType as Class<?>, but there is room in the interface for it to be
            // some other Type. We'll assume it's a Class.
            // TODO: consider logging or throwing our own exception for that day when "something else" causes some confusion
            return (Class) rawType;
        }

        if (actualType instanceof GenericArrayType) {
            final Type type = ((GenericArrayType) actualType)
                    .getGenericComponentType();
            return Array.newInstance(asClass(type), 0).getClass();
        }

        if (actualType instanceof TypeVariable) {
            // Support for List<T extends Number>
            // There is always at least one bound. If no bound is specified in the source then it will be Object.class
            return asClass(((TypeVariable) actualType).getBounds()[0]);
        }

        if (actualType instanceof WildcardType) {
            final WildcardType wildcardType = (WildcardType) actualType;
            final Type[] bounds = wildcardType.getLowerBounds();
            if (bounds != null && bounds.length > 0) {
                return asClass(bounds[0]);
            }
            // If there is no lower bounds then the only thing that makes sense is Object.
            return Object.class;
        }

        throw new RuntimeException(String.format(
                "Unable to convert %s to Class.", actualType));
    }
}

Related Tutorials