Here you can find the source of getGenericFirstClass(Type type)
Parameter | Description |
---|---|
type | The type that has the generic type. (NotNull) |
public static Class<?> getGenericFirstClass(Type type)
//package com.java2s; /*/* w w w .j av a2 s .co m*/ * Copyright 2015-2016 the original author or authors. * * Licensed 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.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; public class Main { protected static final Type[] EMPTY_TYPES = new Type[0]; /** * @param type The type that has the generic type. (NotNull) * @return The first generic type for the specified type. (NullAllowed: e.g. not found) */ public static Class<?> getGenericFirstClass(Type type) { return findGenericClass(type, 0); } protected static Class<?> findGenericClass(Type type, int index) { return getRawClass(getGenericParameterType(type, index)); } public static Class<?> getRawClass(final Type type) { if (Class.class.isInstance(type)) { return Class.class.cast(type); } if (ParameterizedType.class.isInstance(type)) { final ParameterizedType parameterizedType = ParameterizedType.class .cast(type); return getRawClass(parameterizedType.getRawType()); } if (WildcardType.class.isInstance(type)) { final WildcardType wildcardType = WildcardType.class.cast(type); final Type[] types = wildcardType.getUpperBounds(); return getRawClass(types[0]); } if (GenericArrayType.class.isInstance(type)) { final GenericArrayType genericArrayType = GenericArrayType.class .cast(type); final Class<?> rawClass = getRawClass(genericArrayType .getGenericComponentType()); return Array.newInstance(rawClass, 0).getClass(); } return null; } public static Type getGenericParameterType(final Type type, final int index) { if (!ParameterizedType.class.isInstance(type)) { return null; } final Type[] genericParameter = getGenericParameterTypes(type); if (genericParameter.length == 0 || genericParameter.length < index) { return null; } return genericParameter[index]; } public static Type[] getGenericParameterTypes(final Type type) { if (ParameterizedType.class.isInstance(type)) { return ParameterizedType.class.cast(type) .getActualTypeArguments(); } if (GenericArrayType.class.isInstance(type)) { return getGenericParameterTypes(GenericArrayType.class.cast( type).getGenericComponentType()); } return EMPTY_TYPES; } }