Example usage for org.apache.commons.lang3.reflect ConstructorUtils invokeConstructor

List of usage examples for org.apache.commons.lang3.reflect ConstructorUtils invokeConstructor

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect ConstructorUtils invokeConstructor.

Prototype

public static <T> T invokeConstructor(final Class<T> cls, Object... args) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException 

Source Link

Document

Returns a new instance of the specified class inferring the right constructor from the types of the arguments.

This locates and calls a constructor.

Usage

From source file:gobblin.runtime.locks.JobLockFactory.java

/**
 * Gets an instance of {@link JobLock}./*from  w w  w  .j a  va 2  s .  co  m*/
 *
 * @param properties the properties used to determine which instance of {@link JobLock} to create and the
 *                   relevant settings
 * @param jobLockEventListener the {@link JobLock} event listener
 * @return an instance of {@link JobLock}
 * @throws JobLockException throw when the {@link JobLock} fails to initialize
 */
public static JobLock getJobLock(Properties properties, JobLockEventListener jobLockEventListener)
        throws JobLockException {
    Preconditions.checkNotNull(properties);
    Preconditions.checkNotNull(jobLockEventListener);
    JobLock jobLock;
    if (properties.containsKey(ConfigurationKeys.JOB_LOCK_TYPE)) {
        try {
            Class<?> jobLockClass = Class.forName(
                    properties.getProperty(ConfigurationKeys.JOB_LOCK_TYPE, FileBasedJobLock.class.getName()));
            jobLock = (JobLock) ConstructorUtils.invokeConstructor(jobLockClass, properties);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | NoSuchMethodException | InvocationTargetException e) {
            throw new JobLockException(e);
        }
    } else {
        jobLock = new FileBasedJobLock(properties);
    }
    if (jobLock instanceof ListenableJobLock) {
        ((ListenableJobLock) jobLock).setEventListener(jobLockEventListener);
    }
    return jobLock;
}

From source file:gobblin.metrics.context.filter.ContextFilterFactory.java

/**
 * Create a {@link ContextFilter} from a {@link Config}.
 * @param config {@link Config} used for creating new {@link ContextFilter}.
 * @return a new {@link ContextFilter}./*from   w ww. ja v a2s.  c o m*/
 */
public static ContextFilter createContextFilter(Config config) {
    // For now always return an accept-all context filter.
    if (config.hasPath(CONTEXT_FILTER_CLASS)) {
        try {
            return ContextFilter.class.cast(ConstructorUtils
                    .invokeConstructor(Class.forName(config.getString(CONTEXT_FILTER_CLASS)), config));
        } catch (ReflectiveOperationException rfe) {
            log.error(
                    "Failed to instantiate context filter with class " + config.getString(CONTEXT_FILTER_CLASS),
                    rfe);
        }
    }
    return new AllContextFilter();
}

From source file:gobblin.kafka.schemareg.KafkaSchemaRegistryFactory.java

@SuppressWarnings("unchecked")
public static KafkaSchemaRegistry getSchemaRegistry(Properties props) {
    Preconditions.checkArgument(//from ww  w.j  a  va 2 s .  c  o  m
            props.containsKey(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS),
            "Missing required property " + KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS);

    boolean tryCache = Boolean.parseBoolean(props.getProperty(
            KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CACHE, DEFAULT_TRY_CACHING));

    Class<?> clazz;
    try {
        clazz = (Class<?>) Class
                .forName(props.getProperty(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS));
        KafkaSchemaRegistry schemaRegistry = (KafkaSchemaRegistry) ConstructorUtils.invokeConstructor(clazz,
                props);
        if (tryCache && !schemaRegistry.hasInternalCache()) {
            schemaRegistry = new CachingKafkaSchemaRegistry(schemaRegistry);
        }
        return schemaRegistry;
    } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
            | InstantiationException e) {
        log.error("Failed to instantiate " + KafkaSchemaRegistry.class, e);
        throw Throwables.propagate(e);
    }
}

From source file:com.metawiring.load.generator.GeneratorInstantiator.java

@SuppressWarnings("unchecked")
public synchronized Generator getGenerator(String generatorSpec) {

    Class<Generator> generatorClass = (Class<Generator>) resolveGeneratorClass(generatorSpec);
    Object[] generatorArgs = parseGeneratorArgs(generatorSpec);

    try {//www.j a v  a  2  s .  c  o  m
        return ConstructorUtils.invokeConstructor(generatorClass, generatorArgs);
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }

}

From source file:com.uber.hoodie.utilities.UtilHelpers.java

public static SchemaProvider createSchemaProvider(String schemaProviderClass, PropertiesConfiguration cfg)
        throws IOException {
    try {/*  ww  w.j a v  a 2  s  . com*/
        return (SchemaProvider) ConstructorUtils.invokeConstructor(Class.forName(schemaProviderClass),
                (Object) cfg);
    } catch (Throwable e) {
        throw new IOException("Could not load schema provider class " + schemaProviderClass, e);
    }
}

From source file:gobblin.util.reflection.GobblinConstructorUtils.java

/**
 * 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// ww  w  .j ava  2 s.com
 *
 * @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");
}

From source file:gobblin.hive.HiveSchemaManager.java

/**
 * Get an instance of {@link HiveSchemaManager}.
 *
 * @param type The {@link HiveSchemaManager} type. It could be AVRO, NOP or the name of a class that implements
 * {@link HiveSchemaManager}. The specified {@link HiveSchemaManager} type must have a constructor that takes a
 * {@link State} object.//w w w. j  a va2 s .c om
 * @param props A {@link State} object used to instantiate {@link HiveSchemaManager}.
 */
public static HiveSchemaManager getInstance(String type, State props) {
    Optional<Implementation> implementation = Enums.getIfPresent(Implementation.class, type.toUpperCase());
    if (implementation.isPresent()) {
        try {
            return (HiveSchemaManager) ConstructorUtils
                    .invokeConstructor(Class.forName(implementation.get().toString()), props);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(
                    "Unable to instantiate " + HiveSchemaManager.class.getSimpleName() + " with type " + type,
                    e);
        }
    } else {
        log.info(String.format("%s with type %s does not exist. Using %s",
                HiveSchemaManager.class.getSimpleName(), type, HiveNopSchemaManager.class.getSimpleName()));
        return new HiveNopSchemaManager(props);
    }
}

From source file:com.uber.hoodie.utilities.UtilHelpers.java

public static KeyGenerator createKeyGenerator(String keyGeneratorClass, PropertiesConfiguration cfg)
        throws IOException {
    try {//w  ww  . j  av a 2 s .c o m
        return (KeyGenerator) ConstructorUtils.invokeConstructor(Class.forName(keyGeneratorClass),
                (Object) cfg);
    } catch (Throwable e) {
        throw new IOException("Could not load key generator class " + keyGeneratorClass, e);
    }
}

From source file:com.uber.hoodie.DataSourceUtils.java

/**
 * Create a key generator class via reflection, passing in any configs needed
 *//*from  w  w w.  j a v a  2s  . c  om*/
public static KeyGenerator createKeyGenerator(String keyGeneratorClass, PropertiesConfiguration cfg)
        throws IOException {
    try {
        return (KeyGenerator) ConstructorUtils.invokeConstructor(Class.forName(keyGeneratorClass),
                (Object) cfg);
    } catch (Throwable e) {
        throw new IOException("Could not load key generator class " + keyGeneratorClass, e);
    }
}

From source file:com.metawiring.load.activity.dispensers.DirectImplActivityDispenser.java

@Override
public Activity getNewInstance() {
    Activity activity;/*  w  w  w  .  j  av a  2s .  c  om*/
    try {
        activity = (Activity) ConstructorUtils.invokeConstructor(activityClass, new Object[] {});
    } catch (Exception e) {
        logger.error("Error instantiating " + activityClass.getCanonicalName() + ": " + e.getMessage());
        throw new RuntimeException(e);
    }
    return activity;
}