Java Code Examples for org.apache.commons.lang3.reflect.ConstructorUtils#getMatchingAccessibleConstructor()

The following examples show how to use org.apache.commons.lang3.reflect.ConstructorUtils#getMatchingAccessibleConstructor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UIComponentRegistry.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate a given class.
 *
 * @param currentClass
 *            Class to instantiate.
 * @param args
 *            Arguments for the class constructor.
 * @return New instance, what else?
 */
private static <T> T instantiate(Class<? extends T> currentClass, Object... args) {
    T instance = null;

    Log.debug("Args: " + Arrays.toString(args));
    Class<? extends Object>[] classes = new Class<?>[args.length];
    try {
        for (int i = 0; i < args.length; i++) {
            classes[i] = args[i].getClass();
        }
        final Constructor<? extends T> ctor = ConstructorUtils.getMatchingAccessibleConstructor(currentClass, classes);
        instance = ctor.newInstance(args);
    } catch (final Exception e) {
        // not pretty but we're catching several exceptions we can do little
        // about
        Log.error("Error calling constructor for " + currentClass.getName() + " with arguments " + classes, e);
    }
    return instance;
}
 
Example 2
Source File: GobblinConstructorUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of the <code>cls</code> based on a set of arguments. The method will search for a
 * constructor accepting the first k arguments in <code>args</code> for every k from args.length to 0, and will
 * invoke the first constructor found.
 *
 * For example, {@link #invokeLongestConstructor}(cls, myString, myInt) will first attempt to create an object with
 * of class <code>cls</code> with constructor <init>(String, int), if it fails it will attempt <init>(String), and
 * finally <init>().
 *
 * @param cls the class to instantiate.
 * @param args the arguments to use for instantiation.
 * @throws ReflectiveOperationException
 */
public static <T> T invokeLongestConstructor(Class<T> cls, Object... args) throws ReflectiveOperationException {

  Class<?>[] parameterTypes = new Class[args.length];
  for (int i = 0; i < args.length; i++) {
    parameterTypes[i] = args[i].getClass();
  }

  for (int i = args.length; i >= 0; i--) {
    if (ConstructorUtils.getMatchingAccessibleConstructor(cls, Arrays.copyOfRange(parameterTypes, 0, i)) != null) {
      log.debug(
          String.format("Found accessible constructor for class %s with parameter types %s.", cls,
              Arrays.toString(Arrays.copyOfRange(parameterTypes, 0, i))));
      return ConstructorUtils.invokeConstructor(cls, Arrays.copyOfRange(args, 0, i));
    }
  }
  throw new NoSuchMethodException(String.format("No accessible constructor for class %s with parameters a subset of %s.",
      cls, Arrays.toString(parameterTypes)));
}
 
Example 3
Source File: GobblinConstructorUtils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method on top of {@link ConstructorUtils#invokeConstructor(Class, Object[])} that returns a new
 * instance of the <code>cls</code> based on a constructor priority order. Each {@link List} in the
 * <code>constructorArgs</code> array contains the arguments for a constructor of <code>cls</code>. The first
 * constructor whose signature matches the argument types will be invoked.
 *
 * @param cls the class to be instantiated
 * @param constructorArgs An array of constructor argument list. Order defines the priority of a constructor.
 * @return
 *
 * @throws NoSuchMethodException if no constructor matched was found
 */
@SafeVarargs
public static <T> T invokeFirstConstructor(Class<T> cls, List<Object>... constructorArgs)
    throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  for (List<Object> args : constructorArgs) {

    Class<?>[] parameterTypes = new Class[args.size()];
    for (int i = 0; i < args.size(); i++) {
      parameterTypes[i] = args.get(i).getClass();
    }

    if (ConstructorUtils.getMatchingAccessibleConstructor(cls, parameterTypes) != null) {
      return ConstructorUtils.invokeConstructor(cls, args.toArray(new Object[args.size()]));
    }
  }
  throw new NoSuchMethodException("No accessible constructor found");
}
 
Example 4
Source File: LoginCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public LoginCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledLoginCallback();
    }
}
 
Example 5
Source File: UserDateFormatterFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public AbstractUserDateFormatter create(final String timezone) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, timezone.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", timezone.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(timezone);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 6
Source File: AlertCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public AlertCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledAlertCallback();
    }
}
 
Example 7
Source File: HostKeyCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public HostKeyCallback create(final Controller c, final Protocol protocol) {
    if(Scheme.sftp.equals(protocol.getScheme())) {
        try {
            if(null == constructor) {
                constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, c.getClass());
            }
            if(null == constructor) {
                log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
                // Call default constructor for disabled implementations
                return clazz.newInstance();
            }
            return constructor.newInstance(c);
        }
        catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
            log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
            return new DisabledHostKeyCallback();
        }
    }
    return new DisabledHostKeyCallback();
}
 
Example 8
Source File: VaultFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
private Vault create(final Path directory, final String masterkey, final byte[] pepper) {
    try {
        final Constructor<Vault> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz,
            directory.getClass(), masterkey.getClass(), pepper.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", directory.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(directory, masterkey, pepper);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return Vault.DISABLED;
    }
}
 
Example 9
Source File: CertificateTrustCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public CertificateTrustCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledCertificateTrustCallback();
    }
}
 
Example 10
Source File: ThreadPoolFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param size     Maximum pool size
 * @param priority Thread priority
 * @param handler  Uncaught thread exception handler
 */
protected ThreadPool create(final String prefix, final Integer size, final ThreadPool.Priority priority, final Thread.UncaughtExceptionHandler handler) {
    try {
        final Constructor<ThreadPool> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz,
            prefix.getClass(), size.getClass(), priority.getClass(), handler.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", handler.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(prefix, size, priority, handler);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 11
Source File: PasswordCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public PasswordCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledPasswordCallback();
    }
}
 
Example 12
Source File: CertificateIdentityCallbackFactory.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public CertificateIdentityCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledCertificateIdentityCallback();
    }
}
 
Example 13
Source File: TransferErrorCallbackControllerFactory.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public TransferErrorCallback create(final Controller c) {
    try {
        final Constructor<TransferErrorCallback> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, c.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(c);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledTransferErrorCallback();
    }
}
 
Example 14
Source File: ReflectionHelper.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates an object by appropriate constructor.
 * @param cls       class
 * @param params    constructor arguments
 * @return          created object instance
 * @throws NoSuchMethodException    if the class has no constructor matching the given arguments
 */
public static <T> T newInstance(Class<T> cls, Object... params) throws NoSuchMethodException {
    Class[] paramTypes = getParamTypes(params);

    Constructor<T> constructor = ConstructorUtils.getMatchingAccessibleConstructor(cls, paramTypes);
    if (constructor == null)
        throw new NoSuchMethodException(
                String.format("Cannot find a matching constructor for %s and given parameters", cls.getName()));
    try {
        return constructor.newInstance(params);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException("Cannot create instance of " + cls, e);
    }
}
 
Example 15
Source File: SessionFactory.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public static Session<?> create(final Host host, final X509TrustManager trust, final X509KeyManager key) {
    if(log.isDebugEnabled()) {
        log.debug(String.format("Create session for %s", host));
    }
    final Protocol protocol = host.getProtocol();
    final String prefix = protocol.getPrefix();

    try {
        final Class<Session> name = (Class<Session>) Class.forName(String.format("%sSession", prefix));
        final Constructor<Session> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
                host.getClass(), trust.getClass(), key.getClass());
        final Session<?> session;
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s, %s, %s", host.getClass(), trust.getClass(), key.getClass()));
            final Constructor<Session> fallback = ConstructorUtils.getMatchingAccessibleConstructor(name,
                    host.getClass());
            if(fallback == null) {
                throw new FactoryException(String.format("No matching constructor for parameter %s", host.getClass()));
            }
            session = fallback.newInstance(host);
        }
        else {
            session = constructor.newInstance(host, trust, key);
        }
        return session;
    }
    catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
        throw new FactoryException(String.format("Failure loading session class for %s protocol. Failure %s", protocol, e));
    }
}
 
Example 16
Source File: ReflectionUtils.java    From kafka-connect-fs with Apache License 2.0 5 votes vote down vote up
private static <T> T make(Class<T> clazz, Object... args) {
    try {
        Class[] constClasses = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);

        Constructor<T> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, constClasses);
        return constructor.newInstance(args);
    } catch (IllegalAccessException |
            InstantiationException |
            InvocationTargetException e) {
        throw new ConnectException(e.getCause());
    }
}
 
Example 17
Source File: PeriodicUpdateCheckerFactory.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public PeriodicUpdateChecker create(final Controller controller) {
    try {
        final Constructor<PeriodicUpdateChecker> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledPeriodicUpdater();
    }
}
 
Example 18
Source File: DeserializerFactory.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public Deserializer<T> create(final T dict) {
    try {
        final Constructor<Deserializer> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, dict.getClass());
        return constructor.newInstance(dict);
    }
    catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 19
Source File: LocalFactory.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
protected Local create(final Local parent, final String path) {
    try {
        final Constructor<Local> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, parent.getClass(), path.getClass());
        return constructor.newInstance(parent, path);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}