集册 Java实例教程 获取反映类型表示的类。

获取反映类型表示的类。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

535
获取反映类型表示的类。

// Copyright 2008, 2010 The Apache Software Foundation

//package com.nowjava;

import java.lang.reflect.*;

/*
n o w    j a v a  . c o m 提 供
*/

public class Main {

    /**

     * 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/*时 代 J a v a 提供*/

            // 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 
展开阅读全文