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.jims.oauth2.common.utils.OAuthUtils.java

public static <T> T instantiateClassWithParameters(Class<T> clazz, Class<?>[] paramsTypes, Object[] paramValues)
        throws OAuthSystemException {

    try {//from w  w  w.  j  av  a  2 s  .c  o  m
        if (paramsTypes != null && paramValues != null) {
            if (!(paramsTypes.length == paramValues.length)) {
                throw new IllegalArgumentException("Number of types and values must be equal");
            }

            if (paramsTypes.length == 0 && paramValues.length == 0) {
                return clazz.newInstance();
            }
            Constructor<T> clazzConstructor = clazz.getConstructor(paramsTypes);
            return clazzConstructor.newInstance(paramValues);
        }
        return clazz.newInstance();

    } catch (NoSuchMethodException e) {
        throw new OAuthSystemException(e);
    } catch (InstantiationException e) {
        throw new OAuthSystemException(e);
    } catch (IllegalAccessException e) {
        throw new OAuthSystemException(e);
    } catch (InvocationTargetException e) {
        throw new OAuthSystemException(e);
    }

}

From source file:com.googlecode.android_scripting.rpc.MethodDescriptor.java

@SuppressWarnings("rawtypes")
private static Converter<?> converterFor(Type parameterType, Class<? extends Converter> converterClass) {
    if (converterClass == Converter.class) {
        Converter<?> converter = sConverters.get(parameterType);
        if (converter == null) {
            throw new IllegalArgumentException("No predefined converter found for " + parameterType);
        }//from   w  w w . j a  v  a  2s  .  co  m
        return converter;
    }
    try {
        Constructor<?> constructor = converterClass.getConstructor(new Class<?>[0]);
        return (Converter<?>) constructor.newInstance(new Object[0]);
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot create converter from " + converterClass.getCanonicalName());
    }
}

From source file:de.julielab.jcore.utility.JCoReAnnotationTools.java

/**
 * returns an annotation object (de.julielab.jcore.types.annotation) of the type specified by fullEntityClassName.
 * This is done by means of dynamic class loading and reflection.
 * //  w  ww . j av  a2s . c  om
 * @param aJCas
 *            the jcas to which to link this annotation object
 * @param fullAnnotationClassName
 *            the full class name of the new annotation object
 * @return
 */
public static Annotation getAnnotationByClassName(JCas aJCas, String fullAnnotationClassName)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    Class[] parameterTypes = new Class[] { JCas.class };
    Class myNewClass = Class.forName(fullAnnotationClassName);
    Constructor myConstructor = myNewClass.getConstructor(parameterTypes);
    Annotation anno = (Annotation) myConstructor.newInstance(aJCas);
    return anno;
}

From source file:com.igormaznitsa.upom.UPomModel.java

private static Map cloneMap(final Map map) throws Exception {
    final Class mapClass = map.getClass();
    final Constructor constructor = mapClass.getConstructor(Map.class);
    return (Map) constructor.newInstance(map);
}

From source file:org.openqa.grid.internal.BaseRemoteProxy.java

/**
 * Takes a registration request and return the RemoteProxy associated to it. It can be any class
 * extending RemoteProxy.//from   ww  w  .j  a v  a2s  .  c o m
 *
 * @param request  The request
 * @param registry The registry to use
 * @return a new instance built from the request.
 */
@SuppressWarnings("unchecked")
public static <T extends RemoteProxy> T getNewInstance(RegistrationRequest request, Registry registry) {
    try {
        String proxyClass = request.getRemoteProxyClass();
        if (proxyClass == null) {
            log.fine("No proxy class. Using default");
            proxyClass = BaseRemoteProxy.class.getCanonicalName();
        }
        Class<?> clazz = Class.forName(proxyClass);
        log.fine("Using class " + clazz.getName());
        Object[] args = new Object[] { request, registry };
        Class<?>[] argsClass = new Class[] { RegistrationRequest.class, Registry.class };
        Constructor<?> c = clazz.getConstructor(argsClass);
        Object proxy = c.newInstance(args);
        if (proxy instanceof RemoteProxy) {
            ((RemoteProxy) proxy).setupTimeoutListener();
            return (T) proxy;
        } else {
            throw new InvalidParameterException("Error: " + proxy.getClass() + " isn't a remote proxy");
        }

    } catch (InvocationTargetException e) {
        log.log(Level.SEVERE, e.getTargetException().getMessage(), e.getTargetException());
        throw new InvalidParameterException("Error: " + e.getTargetException().getMessage());

    } catch (Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new InvalidParameterException("Error: " + e.getMessage());
    }
}

From source file:com.springframework.beans.BeanUtils.java

/**
 * Convenience method to instantiate a class using the given constructor.
 * As this method doesn't try to load classes by name, it should avoid
 * class-loading issues./*from  w w  w.j  a v  a  2  s.co  m*/
 * <p>Note that this method tries to set the constructor accessible
 * if given a non-accessible (that is, non-public) constructor.
 * @param ctor the constructor to instantiate
 * @param args the constructor arguments to apply
 * @return the new instance
 * @throws BeanInstantiationException if the bean cannot be instantiated
 */
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
    Assert.notNull(ctor, "Constructor must not be null");
    try {
        ReflectionUtils.makeAccessible(ctor);
        return ctor.newInstance(args);
    } catch (InstantiationException ex) {
        throw new BeanInstantiationException(ctor.getDeclaringClass(), "Is it an abstract class?", ex);
    } catch (IllegalAccessException ex) {
        throw new BeanInstantiationException(ctor.getDeclaringClass(), "Is the constructor accessible?", ex);
    } catch (IllegalArgumentException ex) {
        throw new BeanInstantiationException(ctor.getDeclaringClass(), "Illegal arguments for constructor", ex);
    } catch (InvocationTargetException ex) {
        throw new BeanInstantiationException(ctor.getDeclaringClass(), "Constructor threw exception",
                ex.getTargetException());
    }
}

From source file:com.microsoft.tfs.client.common.git.utils.GitHelpers.java

public static Object getInstance(final String pluginName, final String className,
        final Class<?>[] constructorParameterTypes, final Object[] constructorParameterValues) {
    Check.notNullOrEmpty(pluginName, "pluginName"); //$NON-NLS-1$
    Check.notNullOrEmpty(className, "className"); //$NON-NLS-1$
    Check.notNull(constructorParameterTypes, "constructorParameterTypes"); //$NON-NLS-1$
    Check.notNull(constructorParameterTypes, "constructorParameterTypes"); //$NON-NLS-1$

    final Class<?> operationClass = getClass(pluginName, className);
    if (operationClass == null) {
        return null;
    }/*from   w  ww.  j ava  2s .  c o  m*/

    final Constructor<?> constructor;
    try {
        constructor = operationClass.getDeclaredConstructor(constructorParameterTypes);
        constructor.setAccessible(true);
    } catch (final Exception e) {
        log.error("Searching for the " + operationClass.getName() + " constructor", e); //$NON-NLS-1$ //$NON-NLS-2$
        return null;
    }

    final Object operationInstance;
    try {
        operationInstance = constructor.newInstance(constructorParameterValues);
    } catch (final Exception e) {
        log.error("Creating the " + operationClass.getName() + " object", e); //$NON-NLS-1$ //$NON-NLS-2$
        return null;
    }

    return operationInstance;
}

From source file:libepg.epg.section.body.eventinformationtable.EventInformationTableBodyTest.java

private static final EventInformationTableRepeatingPart init(byte[] data) throws InvocationTargetException {
    try {// w w w . j ava2 s.  co m
        Object[] args = { data };
        Class<?>[] params = { byte[].class };
        Constructor<EventInformationTableRepeatingPart> constructor = EventInformationTableRepeatingPart.class
                .getDeclaredConstructor(params);
        constructor.setAccessible(true);
        EventInformationTableRepeatingPart target = constructor.newInstance(args);
        return target;
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException
            | SecurityException ex) {
        LOG.fatal(ex);
    }
    return null;
}

From source file:com.igormaznitsa.upom.UPomModel.java

private static Collection cloneCollection(final Collection collection) throws Exception {
    final Class collectionClass = collection.getClass();
    final Constructor constructor = collectionClass.getConstructor(Collection.class);
    return (Collection) constructor.newInstance(collection);
}

From source file:ml.shifu.shifu.util.ClassUtils.java

public static <T> T newInstance(Class<T> clazz, Class<?>[] parameterClasses, Object[] parameters) {
    T result;//  w  w w.  ja va2 s . co  m
    try {
        @SuppressWarnings("unchecked")
        Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(clazz);
        if (meth == null) {
            meth = clazz.getDeclaredConstructor(parameterClasses);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(clazz, meth);
        }
        result = meth.newInstance(parameters);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}