ReflectionUtils.java

  1. /*
  2.  * *********************************************************************************************************************
  3.  *
  4.  * TheseFoolishThings: Miscellaneous utilities
  5.  * http://tidalwave.it/projects/thesefoolishthings
  6.  *
  7.  * Copyright (C) 2009 - 2023 by Tidalwave s.a.s. (http://tidalwave.it)
  8.  *
  9.  * *********************************************************************************************************************
  10.  *
  11.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  12.  * the License. You may obtain a copy of the License at
  13.  *
  14.  *     http://www.apache.org/licenses/LICENSE-2.0
  15.  *
  16.  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  17.  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
  18.  * specific language governing permissions and limitations under the License.
  19.  *
  20.  * *********************************************************************************************************************
  21.  *
  22.  * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src
  23.  * git clone https://github.com/tidalwave-it/thesefoolishthings-src
  24.  *
  25.  * *********************************************************************************************************************
  26.  */
  27. package it.tidalwave.util;

  28. import java.lang.reflect.Array;
  29. import java.lang.reflect.GenericArrayType;
  30. import java.lang.reflect.ParameterizedType;
  31. import java.lang.reflect.Type;
  32. import java.lang.reflect.TypeVariable;
  33. import javax.annotation.Nonnull;
  34. import java.util.ArrayList;
  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Map;
  38. import static java.util.Objects.requireNonNull;

  39. /***********************************************************************************************************************
  40.  *
  41.  * Just slightly adapted from <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860">this article</a>.
  42.  *
  43.  * @author Ian Robertson
  44.  * @author Fabrizio Giudici
  45.  *
  46.  **********************************************************************************************************************/
  47. public class ReflectionUtils
  48.   {
  49.     /*******************************************************************************************************************
  50.      *
  51.      * Get the actual type arguments a subclass has used to extend a generic base class.
  52.      *
  53.      * @param   <T>           the static type of the base class
  54.      * @param   baseClass     the base class
  55.      * @param   childClass    the subclass
  56.      * @return                a list of the raw classes for the actual type arguments.
  57.      *
  58.      ******************************************************************************************************************/
  59.     @Nonnull
  60.     public static <T> List<Class<?>> getTypeArguments (@Nonnull final Class<T> baseClass,
  61.                                                        @Nonnull final Class<? extends T> childClass)
  62.       {
  63.         final Map<Type, Type> resolvedTypes = new HashMap<>();
  64.         Type type = childClass;

  65.         // start walking up the inheritance hierarchy until we hit baseClass
  66.         while (!getClass(type).equals(baseClass))
  67.           {
  68.             if (type instanceof Class<?>)
  69.               {
  70.                 // there is no useful information for us in raw types, so just keep going.
  71.                 type = ((Class<?>)type).getGenericSuperclass();
  72.               }
  73.             else
  74.               {
  75.                 final var parameterizedType = (ParameterizedType) type;
  76.                 final var rawType = (Class<?>) parameterizedType.getRawType();
  77.                 final var actualTypeArguments = parameterizedType.getActualTypeArguments();
  78.                 final TypeVariable<?>[] typeParameters = rawType.getTypeParameters();

  79.                 for (var i = 0; i < actualTypeArguments.length; i++)
  80.                   {
  81.                     resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
  82.                   }

  83.                 if (!rawType.equals(baseClass))
  84.                   {
  85.                     type = rawType.getGenericSuperclass();
  86.                   }
  87.               }
  88.           }

  89.         // finally, for each actual type argument provided to baseClass, determine (if possible)
  90.         // the raw class for that type argument.
  91.         final Type[] actualTypeArguments;

  92.         if (type instanceof Class)
  93.           {
  94.             actualTypeArguments = ((Class<?>)type).getTypeParameters();
  95.           }
  96.         else
  97.           {
  98.             actualTypeArguments = ((ParameterizedType)type).getActualTypeArguments();
  99.           }

  100.         final List<Class<?>> typeArgumentsAsClasses = new ArrayList<>();
  101.         // resolve types by chasing down type variables.
  102.         for (var baseType : actualTypeArguments)
  103.           {
  104.             while (resolvedTypes.containsKey(baseType))
  105.               {
  106.                 baseType = resolvedTypes.get(baseType);
  107.               }

  108.             typeArgumentsAsClasses.add(getClass(baseType));
  109.           }

  110.         return typeArgumentsAsClasses;
  111.       }

  112.     @Nonnull
  113.     public static Class<?> getClass (@Nonnull final Type type)
  114.       {
  115.         requireNonNull(type, "type");

  116.         if (type instanceof Class<?>)
  117.           {
  118.             return (Class<?>)type;
  119.           }
  120.         else if (type instanceof ParameterizedType)
  121.           {
  122.             return getClass(((ParameterizedType)type).getRawType());
  123.           }
  124.         else if (type instanceof GenericArrayType)
  125.           {
  126.             final var componentType = ((GenericArrayType)type).getGenericComponentType();
  127.             final var componentClass = getClass(componentType);
  128.             return Array.newInstance(componentClass, 0).getClass();
  129.           }

  130.         throw new IllegalArgumentException(type.toString());
  131.       }
  132.   }