Example usage for java.lang.reflect Constructor newInstance

List of usage examples for java.lang.reflect Constructor newInstance

Introduction

In this page you can find the example usage for java.lang.reflect Constructor newInstance.

Prototype

@CallerSensitive
@ForceInline 
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException 

Source Link

Document

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

Usage

From source file:com.cenrise.test.azkaban.Utils.java

/**
 * Call the class constructor with the given arguments
 *
 * @param c The class/*from  w  ww .  j a va2 s .co m*/
 * @param args The arguments
 * @return The constructed object
 */
public static Object callConstructor(final Class<?> c, final Class<?>[] argTypes, final Object[] args) {
    try {
        final Constructor<?> cons = c.getConstructor(argTypes);
        return cons.newInstance(args);
    } catch (final InvocationTargetException e) {
        throw getCause(e);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (final NoSuchMethodException e) {
        throw new IllegalStateException(e);
    } catch (final InstantiationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.itransformers.idiscover.core.DiscoveryManager.java

private static DiscoveryHelperFactory createDiscoveryHelperFactory(DiscoveryManagerType discoveryManagerType)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        InvocationTargetException {
    net.itransformers.idiscover.core.discoveryconfig.DiscoveryHelperType discoveryHelperType = discoveryManagerType
            .getDiscoveryHelper();/*from ww  w. ja va2s. c  om*/
    String clazzStr = discoveryHelperType.getClazz();
    Class<?> clazz = Class.forName(clazzStr);
    Map<String, String> discoveryHelerpParams = new HashMap<String, String>();

    for (ParamType s : discoveryHelperType.getParameters().getParam()) {
        discoveryHelerpParams.put(s.getName(), s.getValue());
    }
    Constructor constructor = clazz.getConstructor(Map.class);
    return (DiscoveryHelperFactory) constructor.newInstance(discoveryHelerpParams);
}

From source file:com.amalto.core.storage.hibernate.FlatTypeMapping.java

@SuppressWarnings("rawtypes")
private static Serializable createCompositeId(ClassLoader classLoader, Class<?> clazz,
        List<Object> compositeIdValues) {
    try {//from   ww  w.j  av  a  2  s . com
        Class<?> idClass = classLoader.loadClass(clazz.getName() + "_ID"); //$NON-NLS-1$
        Class[] parameterClasses = new Class[compositeIdValues.size()];
        int i = 0;
        for (Object o : compositeIdValues) {
            parameterClasses[i++] = o.getClass();
        }
        Constructor<?> constructor = idClass.getConstructor(parameterClasses);
        return (Serializable) constructor.newInstance(compositeIdValues.toArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.heliosapm.streams.collector.ds.pool.PoolConfig.java

/**
 * Creates and deploys an ObjectPool based on the passed config props
 * @param p The configuration properties
 * @return the created GenericObjectPool
 *///from w  ww . ja va 2s. c om
@SuppressWarnings({ "rawtypes", "unchecked" })
private static GenericObjectPool<?> deployPool(final Properties p) {
    final String factoryName = (String) p.remove(POOLED_OBJECT_FACTORY_KEY);
    final String poolName = p.getProperty(NAME.name().toLowerCase());
    if (poolName == null || poolName.trim().isEmpty())
        throw new RuntimeException("Pool was not assigned a name");
    if (factoryName == null || factoryName.trim().isEmpty())
        throw new RuntimeException("No pooled object factory defined");
    final GenericObjectPoolConfig cfg = DEFAULT_CONFIG.clone();
    try {
        final Class<PooledObjectFactoryBuilder<?>> clazz = loadFactoryClass(factoryName);
        final Constructor<PooledObjectFactoryBuilder<?>> ctor = clazz.getDeclaredConstructor(Properties.class);
        final PooledObjectFactoryBuilder<?> factory = ctor.newInstance(p);
        for (final String key : p.stringPropertyNames()) {
            if (isPoolConfig(key)) {
                final PoolConfig pc = decode(key);
                pc.apply(cfg, p.get(key));
            }
        }
        final PooledObjectFactory<?> pooledObjectFactory = factory.factory();
        GenericObjectPool<?> pool = new GenericObjectPool(pooledObjectFactory, cfg);
        pool.setSwallowedExceptionListener(EX_LISTENER);
        if (factory instanceof PoolAwareFactory) {
            ((PoolAwareFactory) factory).setPool(pool);
        }
        GlobalCacheService.getInstance().put("pool/" + poolName, pool);
        pool.setAbandonedConfig(Abandoned.create(p));
        pool.preparePool();
        return pool;
    } catch (Exception ex) {
        throw new RuntimeException("Failed to create GenericObjectPool from properties [" + p + "]", ex);
    }
}

From source file:com.mani.cucumber.ReflectionUtils.java

public static <T> T newInstance(Class<T> clazz, Object... params) {
    Constructor<T> constructor = findConstructor(clazz, params);

    try {/*from   ww  w .j  a  v a2s. c o  m*/

        return constructor.newInstance(params);

    } catch (InstantiationException | IllegalAccessException ex) {
        throw new IllegalStateException("Could not invoke " + constructor.toGenericString(), ex);

    } catch (InvocationTargetException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            throw (RuntimeException) ex.getCause();
        }
        throw new IllegalStateException(
                "Unexpected checked exception thrown from " + constructor.toGenericString(), ex);
    }
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static Object constructNew(Class<?> clazz, Object[] args)
        throws NoSuchMethodException, InstantiationException, IllegalArgumentException, IllegalAccessException {
    if (args.length < 1) {
        return clazz.newInstance();
    } else {//w ww. j a  v a 2 s.com
        Class<?>[] paramTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            paramTypes[i] = args[i].getClass();
        }

        Constructor<?> con = clazz.getConstructor(paramTypes);

        try {
            return con.newInstance(args);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }
}

From source file:lapin.load.Loader.java

static private Subr _toSubr(Symbol name, Class clazz, Env env) throws InstantiationException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (Logger.debuglevelp(env)) {
        Logger.debug("[toSubr] name  : ~S", Lists.list(name), env);
        Logger.debug("[toSubr] class : ~S", Lists.list(clazz), env);
        Logger.debug("[toSubr] loader: ~S", Lists.list(clazz.getClassLoader()), env);
    }//from   w w w  .j av a  2 s  .  c om
    Constructor c = clazz.getConstructor(CONSTRUCTOR_PARAM_TYPES);
    return Data.subr(c.newInstance(new Object[] { env }));
}

From source file:azkaban.common.utils.Utils.java

/**
 * Call the class constructor with the given arguments
 * //from w w w . ja v  a2 s .  c o  m
 * @param c The class
 * @param args The arguments
 * @return The constructed object
 */
public static Object callConstructor(Class<?> c, Class<?>[] argTypes, Object[] args) {
    try {
        Constructor<?> cons = c.getConstructor(argTypes);
        return cons.newInstance(args);
    } catch (InvocationTargetException e) {
        throw getCause(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(e);
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:de.tbuchloh.kiskis.gui.AbstractAccountDetailView.java

public static AbstractAccountDetailView create(final ModelNode node) {
    final Class<?> c = NODE_MAP.get(node.getClass());
    try {//from  w  w w.  java  2  s .  c om
        final Constructor<?> builder = c.getConstructor(new Class[] { ModelNode.class });
        return (AbstractAccountDetailView) builder.newInstance(new Object[] { node });
    } catch (final Exception e) {
        throw new Error("should never happen!", e); //$NON-NLS-1$
    }
}

From source file:lucee.transformer.bytecode.reflection.ASMProxyFactory.java

private static ASMMethod newInstance(Class<?> asmClass, Class<?> decClass, Class[] params)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, SecurityException, NoSuchMethodException {
    Constructor<ASMMethod> constr = (Constructor<ASMMethod>) asmClass
            .getConstructor(new Class[] { Class.class, Class[].class });
    return constr.newInstance(new Object[] { decClass, params });

    //return (ASMMethod) asmClass.newInstance();
}