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:com.jsen.core.misc.MimeContentRegistryBase.java

/**
 * Constructs MIME content factory from a given class and constructor arguments.
 * //from www  .  j  a v  a  2 s  .c  om
 * @param factoryClass MIME content factory class of which should be constructed the instance.
 * @param args Constructor arguments for factory.
 * @return Constructed MIME content factory on success, otherwise null.
 */
protected MimeContentFactory instantizeMimeContentFactory(Class<? extends MimeContentFactory> factoryClass,
        Object... args) {
    MimeContentFactory mimeContentFactory = null;

    try {
        /*List<Class<?>> constructorClassesList = new ArrayList<Class<?>>();
                
        for (Object arg : args) {
           constructorClassesList.add(arg.getClass());
        }
                
        Class<?> constructorClasses[] = constructorClassesList.toArray(new Class<?>[constructorClassesList.size()]);
                
        Constructor<? extends MimeContentFactoryBase<?>> mimeContentFactoryConstructor = factoryClass.getConstructor(constructorClasses);
        mimeContentFactory = mimeContentFactoryConstructor.newInstance(args);*/

        Object newInstance = ConstructorUtils.invokeConstructor(factoryClass, args);
        mimeContentFactory = factoryClass.cast(newInstance);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return mimeContentFactory;
}

From source file:com.thinkbiganalytics.metadata.modeshape.BaseJcrProvider.java

public <D, R> Iterable<D> findIterable(String query, Class<D> domainClass, Class<R> resultClass) {
    return () -> {
        return StreamSupport.stream(findIterableNodes(query).spliterator(), false).map(node -> {
            try {
                @SuppressWarnings("unchecked")
                D entity = (D) ConstructorUtils.invokeConstructor(resultClass, node);
                return entity;
            } catch (Exception e) {
                throw new MetadataRepositoryException("Failed to create entity: " + resultClass, e);
            }//www . j ava 2s . co m
        }).iterator();
    };
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

private void performCountTest(String testClass) throws Exception {
    StringBuilder builder = new StringBuilder();

    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(testClass + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(testClass);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, builder);

        CoroutineRunner runner = new CoroutineRunner(coroutine);

        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertFalse(runner.execute()); // coroutine finished executing here
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());

        Assert.assertEquals("started\n" + "0\n" + "1\n" + "2\n" + "3\n" + "4\n" + "5\n" + "6\n" + "7\n" + "8\n"
                + "9\n" + "started\n" + "0\n" + "1\n" + "2\n", builder.toString());
    }/*from   w ww  .  j a v  a2 s  . c  o  m*/
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

@Test
public void mustProperlySuspendInTryCatchFinally() throws Exception {
    StringBuilder builder = new StringBuilder();

    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(EXCEPTION_SUSPEND_TEST + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(EXCEPTION_SUSPEND_TEST);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, builder);

        CoroutineRunner runner = new CoroutineRunner(coroutine);

        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertFalse(runner.execute()); // coroutine finished executing here

        Assert.assertEquals("START\n" + "IN TRY 1\n" + "IN TRY 2\n" + "IN CATCH 1\n" + "IN CATCH 2\n"
                + "IN FINALLY 1\n" + "IN FINALLY 2\n" + "END\n", builder.toString());
    }//from  ww  w  .jav  a 2  s .c  o m
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

@Test
public void mustProperlySuspendInTryCatchFinallyWithOldJsrInstructions() throws Exception {
    StringBuffer builder = new StringBuffer();

    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(
            JSR_EXCEPTION_SUSPEND_TEST + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(JSR_EXCEPTION_SUSPEND_TEST);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, builder);

        CoroutineRunner runner = new CoroutineRunner(coroutine);

        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertTrue(runner.execute());
        Assert.assertFalse(runner.execute()); // coroutine finished executing here

        Assert.assertEquals("START\n" + "IN TRY 1\n" + "IN TRY 2\n" + "IN CATCH 1\n" + "IN CATCH 2\n"
                + "IN FINALLY 1\n" + "IN FINALLY 2\n" + "END\n", builder.toString());
    }/*from  ww w  .ja v a  2s .  c om*/
}

From source file:gobblin.hive.policy.HiveRegistrationPolicyBase.java

/**
 * Get a {@link HiveRegistrationPolicy} from a {@link State} object.
 *
 * @param props A {@link State} object that contains property, {@link #HIVE_REGISTRATION_POLICY},
 * which is the class name of the desired policy. This policy class must have a constructor that
 * takes a {@link State} object.//  w  w w . jav  a2s  .  c  om
 */
public static HiveRegistrationPolicy getPolicy(State props) {
    Preconditions.checkArgument(props.contains(ConfigurationKeys.HIVE_REGISTRATION_POLICY));

    String policyType = props.getProp(ConfigurationKeys.HIVE_REGISTRATION_POLICY);
    try {
        return (HiveRegistrationPolicy) ConstructorUtils.invokeConstructor(Class.forName(policyType), props);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to instantiate " + HiveRegistrationPolicy.class.getSimpleName()
                + " with type " + policyType, e);
    }
}

From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java

private P createClass(BaseUiPolicyRule rule) throws ClassNotFoundException, InvocationTargetException,
        NoSuchMethodException, InstantiationException, IllegalAccessException {
    P domainPolicy = null;/*from w ww  . ja  va 2 s .  co m*/
    String classType = rule.getObjectClassType();
    Class<P> domainPolicyClass = (Class<P>) Class.forName(classType);

    Constructor constructor = null;
    Object[] paramValues = null;
    boolean hasConstructor = false;
    for (Constructor con : domainPolicyClass.getConstructors()) {
        hasConstructor = true;
        int parameterSize = con.getParameterTypes().length;
        paramValues = new Object[parameterSize];
        for (int p = 0; p < parameterSize; p++) {
            Annotation[] annotations = con.getParameterAnnotations()[p];
            Object paramValue = null;
            for (Annotation a : annotations) {
                if (a instanceof PolicyPropertyRef) {
                    // this is the one we want
                    if (constructor == null) {
                        constructor = con;
                    }
                    //find the value associated to this property
                    paramValue = getPropertyValue(rule, domainPolicyClass, (PolicyPropertyRef) a);

                }
            }
            paramValues[p] = paramValue;
        }
        if (constructor != null) {
            //exit once we find a constructor with @PropertyRef
            break;
        }

    }

    if (constructor != null) {
        //call that constructor
        try {
            domainPolicy = ConstructorUtils.invokeConstructor(domainPolicyClass, paramValues);
        } catch (NoSuchMethodException e) {
            domainPolicy = domainPolicyClass.newInstance();
        }
    } else {
        //if the class has no public constructor then attempt to call the static instance method
        if (!hasConstructor) {
            //if the class has a static "instance" method on it then call that
            try {
                domainPolicy = (P) MethodUtils.invokeStaticMethod(domainPolicyClass, "instance", null);
            } catch (NoSuchMethodException | SecurityException | InvocationTargetException e) {
                domainPolicy = domainPolicyClass.newInstance();
            }
        } else {
            //attempt to create a new instance
            domainPolicy = domainPolicyClass.newInstance();
        }

    }

    return domainPolicy;

}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrUtil.java

/**
 * Create a new Node Wrapper Object that invokes a constructor with at least parameter of type Node
 *///from  w  w w .j av a 2  s  .  co  m
public static <T extends Object> T constructNodeObject(Node node, Class<T> type, Object... constructorArgs) {
    T entity = null;
    try {
        if (constructorArgs != null) {
            constructorArgs = ArrayUtils.add(constructorArgs, 0, node);
        } else {
            constructorArgs = new Object[] { node };
        }

        entity = ConstructorUtils.invokeConstructor(type, constructorArgs);
    } catch (InvocationTargetException | NoSuchMethodException | InstantiationException
            | IllegalAccessException e) {
        throw new MetadataRepositoryException("Failed to createJcrObject for node " + type, e);
    }
    return entity;
}

From source file:de.tuberlin.uebb.jbop.optimizer.ClassNodeBuilder.java

/**
 * Instantiate the classObject.// w w w  .  jav a2 s  .c o  m
 * 
 * @param params
 *          the params
 * @return the object
 * @throws Exception
 *           the exception
 */
public Object instance(final Object... params) throws Exception {
    if (buildedClass == null) {
        toClass();
    }
    return ConstructorUtils.invokeConstructor(buildedClass, params);
}

From source file:org.apache.gobblin.cluster.ScheduledJobConfigurationManager.java

public ScheduledJobConfigurationManager(EventBus eventBus, Config config) {
    super(eventBus, config);

    this.jobSpecs = Maps.newHashMap();
    this.refreshIntervalInSeconds = ConfigUtils.getLong(config,
            GobblinClusterConfigurationKeys.JOB_SPEC_REFRESH_INTERVAL, DEFAULT_JOB_SPEC_REFRESH_INTERVAL);

    this.fetchJobSpecExecutor = Executors.newSingleThreadScheduledExecutor(
            ExecutorsUtils.newThreadFactory(Optional.of(LOGGER), Optional.of("FetchJobSpecExecutor")));

    this.aliasResolver = new ClassAliasResolver<>(SpecConsumer.class);
    try {//from   www . j av a2  s .  c  o  m
        String specConsumerClassName = GobblinClusterConfigurationKeys.DEFAULT_SPEC_CONSUMER_CLASS;
        if (config.hasPath(GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY)) {
            specConsumerClassName = config.getString(GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY);
        }
        LOGGER.info("Using SpecConsumer ClassNameclass name/alias " + specConsumerClassName);
        this._specConsumer = (SpecConsumer) ConstructorUtils
                .invokeConstructor(Class.forName(this.aliasResolver.resolve(specConsumerClassName)), config);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}