public static T instantiatePlugin()

in core/src/main/java/org/apache/calcite/avatica/AvaticaUtils.java [220:281]


  public static <T> T instantiatePlugin(Class<T> pluginClass,
      String className) {
    String right = null;
    String left = null;
    Object value = null;
    try {
      // Given a static field, say "com.example.MyClass#FOO_INSTANCE", return
      // the value of that static field.
      if (className.contains("#")) {
        int i = className.indexOf('#');
        left = className.substring(0, i);
        right = className.substring(i + 1);
        //noinspection unchecked
        final Class<T> clazz = (Class) Class.forName(left);
        final Field field;
        field = clazz.getField(right);
        final Object fieldValue = field.get(null);
        if (fieldValue instanceof ThreadLocal) {
          value = ((ThreadLocal<?>) fieldValue).get();
        } else {
          value = fieldValue;
        }
        return pluginClass.cast(value);
      }
      //noinspection unchecked
      final Class<T> clazz = (Class) Class.forName(className);
      try {
        // We assume that if there is an INSTANCE field it is static and
        // has the right type.
        final Field field = clazz.getField("INSTANCE");
        value = field.get(null);
        return pluginClass.cast(value);
      } catch (NoSuchFieldException e) {
        // ignore
      }
      if (!pluginClass.isAssignableFrom(clazz)) {
        throw new RuntimeException("Property '" + className
            + "' not valid for plugin type " + pluginClass.getName());
      }
      return clazz.getConstructor().newInstance();
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Property '" + className
          + "' not valid as '" + className + "' not found in the classpath", e);
    } catch (NoSuchFieldException e) {
      // We can't ignore it because the right field is user configured.
      throw new RuntimeException("Property '" + className
          + "' not valid as there is no '" + right + "' field in the class of '"
          + left + "'", e);
    } catch (ClassCastException e) {
      throw new RuntimeException("Property '" + className
          + "' not valid as cannot convert "
          + (value == null ? "null" : value.getClass().getName())
          + " to " + pluginClass.getCanonicalName(), e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException("Property '" + className + "' not valid as "
          + "the default constructor is necessary, "
          + "but not found in the class of '" + className + "'", e);
    } catch (ReflectiveOperationException e) {
      throw new RuntimeException("Property '" + className
          + "' not valid. The exception info here : " + e.getMessage(), e);
    }
  }