检索ParameterizedType,它描述在type的类型层次结构中绑定到declaringClass的参数类型。
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.reflect.GenericDeclaration; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType;/** 时 代 J a v a 公 众 号 - nowjava.com 提 供 **/ import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class Main{ /** * Retrieves the {@link ParameterizedType} that describes the parameter types bound to <code>declaringClass</code> in the type * hierarchy of <code>type</code>. * * @param type The class to be analyzed. * @param declaringClass The class/interface declaring generic parameters. * * @return The {@link ParameterizedType} requested or <code>null</code> if <code>declaringClass</code> does not define any generic * parameters. * * @throws ReflectionException If <code>type</code> is not a subclass of <code>declaringClass</code>. */ public static ParameterizedType getParameterizedType(Class<?> type, Class<?> declaringClass) {//nowjava.com - 时 代 Java 提供 if (!declaringClass.isAssignableFrom(type)) { throw new ReflectionException(type + " is not a subclass of " + declaringClass + "."); } List<Type> types = new LinkedList<Type>(); types.add(type); while (!types.isEmpty()) { Type currentType = types.remove(0); if (currentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) currentType; if (parameterizedType.getRawType().equals(declaringClass)) { return parameterizedType; } } types.addAll(getParents(currentType)); } return null; } private static Collection<Type> getParents(Type type) { Collection<Type> result = new LinkedList<Type>(); if (type instanceof Class) { Class<?> cla