Attempts to create a class of the given type T, containing arguments of the type A. - Android java.lang.reflect

Android examples for java.lang.reflect:Class

Description

Attempts to create a class of the given type T, containing arguments of the type A.

Demo Code


import java.lang.reflect.InvocationTargetException;

import android.util.Log;

public class Main {
  private static final String TAG = "";

  /**//from ww w  .j ava  2s . c  o m
   * Attempts to create a class of the given type T, containing arguments of the
   * type A. Can be used with Void argument class types for constructors without
   * parameters. Will only work in constructors that only take one type of class
   * as arguments. The constructor of the target class must be declared as
   * public, otherwise it won't be reachable. If the class to construct is an
   * inner class, it needs to be static for it to be found.
   *
   * @param typeClass
   *          the class type of the class to instantiate
   * @param argClass
   *          the class type of the argument of the constructor. If it is null
   *          or Void, a constructor with no arguments is called, even if an
   *          argument list is passed.
   * @param arguments
   *          the list of arguments of type A (optional, or 1 element)
   * @param <T>
   *          the type class to instantiate
   * @param <A>
   *          the argument class to pass as parameter
   * @return the instantiated class, or null if an exception was thrown while
   *         trying to instantiate the class
   */
  @SafeVarargs
  public static <T, A> T makeObjectOfType(Class<T> typeClass,
      Class<A> argClass, A... arguments) {
    try {
      if (argClass == null || argClass == Void.class) {
        return typeClass.getDeclaredConstructor().newInstance();
      } else {
        return typeClass.getDeclaredConstructor(argClass)
            .newInstance(arguments);
      }
    } catch (NoSuchMethodException | InstantiationException
        | IllegalAccessException | InvocationTargetException e) {
      Log.e(TAG, e.getMessage() + "");
    }

    return null;
  }
}

Related Tutorials