Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

In this page you can find the example usage for java.lang Class getConstructor.

Prototype

@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Usage

From source file:com.chinamobile.bcbsp.util.ClusterUtil.java

/**
 * Creates a {@link WorkerManagerThread}. Call 'start' on the returned thread
 * to make it run./*from   www  . java  2 s  .  com*/
 *
 * @param c
 *        Configuration to use.
 * @param hrsc
 *        Class to create.
 * @param index
 *        Used distingushing the object returned.
 * @throws IOException
 * @return Groom server added.
 */
public static ClusterUtil.WorkerManagerThread createWorkerManagerThread(final Configuration c,
        final Class<? extends WorkerManager> hrsc, final int index) throws IOException {
    WorkerManager server;
    try {
        server = hrsc.getConstructor(Configuration.class).newInstance(c);
    } catch (Exception e) {
        LOG.error("[createWorkerManagerThread]", e);
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }
    return new ClusterUtil.WorkerManagerThread(server, index);
}

From source file:it.doqui.index.ecmengine.client.engine.EcmEngineDelegateFactory.java

private static EcmEngineDelegate getClassInstance(String ecmEngineDelegateImplName, Log logger)
        throws EcmEngineDelegateInstantiationException {
    EcmEngineDelegate classInstance = null;

    logger.debug("[EcmEngineDelegateFactory::getClassInstance] BEGIN");
    try {//from  w  w  w . j ava2s.  co  m
        logger.debug("[EcmEngineDelegateFactory::getClassInstance] " + "Caricamento classe: "
                + ecmEngineDelegateImplName);
        final Class delegateClass = Class.forName(ecmEngineDelegateImplName);
        final Constructor constructor = delegateClass.getConstructor(new Class[] { Log.class });

        classInstance = (EcmEngineDelegate) constructor.newInstance(new Object[] { logger });
    } catch (ClassNotFoundException e) {
        logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: classe non trovata.");
        throw new EcmEngineDelegateInstantiationException("Classe non trovata.", e);
    } catch (NoSuchMethodException e) {
        logger.error(
                "[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: nessun costruttore compatibile.");
        throw new EcmEngineDelegateInstantiationException("Nessun costruttore compatibile.", e);
    } catch (InstantiationException e) {
        logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: errore di istanziazione.");
        throw new EcmEngineDelegateInstantiationException("Errore di istanziazione.", e);
    } catch (IllegalAccessException e) {
        logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: errore di accesso.");
        throw new EcmEngineDelegateInstantiationException("Errore di accesso.", e);
    } catch (InvocationTargetException e) {
        logger.error("[EcmEngineDelegateFactory::getClassInstance] " + "FATAL: eccezione nel target invocato.");
        throw new EcmEngineDelegateInstantiationException("Eccezione nel target invocato.", e);
    } finally {
        logger.debug("[EcmEngineDelegateFactory::getClassInstance] END");
    }
    return classInstance;
}

From source file:jp.rikinet.util.dto.DtoFactory.java

/**
 * ??????? DTO ??//from   w w w  .  jav  a  2  s.co  m
 * @param cl classTable ???? DTO 
 * @param jo DTO ??????? JSONObject
 * @param <T> DTO ?
 * @return ??? DTO
 */
private static <T extends Root> T newSimpleDto(Class<T> cl, JSONObject jo) {
    T dto;
    try {
        Constructor<T> cons = cl.getConstructor(JSONObject.class);
        dto = cons.newInstance(jo);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("constructor not found", e);
    } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
        throw new IllegalArgumentException("constructor call failed", e);
    }
    return dto;
}

From source file:it.doqui.index.ecmengine.client.backoffice.EcmEngineBackofficeDelegateFactory.java

private static EcmEngineBackofficeDelegate getClassInstance(String ecmEngineBkoDelegateImplName, Log logger)
        throws EcmEngineBackofficeDelegateInstantiationException {
    EcmEngineBackofficeDelegate classInstance = null;

    logger.debug("[EcmEngineBackofficeDelegateFactory::getClassInstance] BEGIN");
    try {//from  w  w w .jav a  2s  . c  o  m
        logger.debug("[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "Caricamento classe: "
                + ecmEngineBkoDelegateImplName);
        final Class delegateClass = Class.forName(ecmEngineBkoDelegateImplName);
        final Constructor constructor = delegateClass.getConstructor(new Class[] { Log.class });
        classInstance = (EcmEngineBackofficeDelegate) constructor.newInstance(new Object[] { logger });
    } catch (ClassNotFoundException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "FATAL: classe non trovata.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Classe non trovata.", e);
    } catch (NoSuchMethodException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] "
                + "FATAL: nessun costruttore compatibile.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Nessun costruttore compatibile.", e);
    } catch (InstantiationException e) {
        logger.error(
                "[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "FATAL: errore di istanziazione.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Errore di istanziazione.", e);
    } catch (IllegalAccessException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "FATAL: errore di accesso.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Errore di accesso.", e);
    } catch (InvocationTargetException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] "
                + "FATAL: eccezione nel target invocato.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Eccezione nel target invocato.", e);
    } finally {
        logger.debug("[EcmEngineBackofficeDelegateFactory::getClassInstance] END");
    }
    return classInstance;
}

From source file:com.dianping.squirrel.client.util.ClassUtils.java

@SuppressWarnings("unchecked")
private static <T> Constructor<T> getMatchingDeclaredConstructor(Class<T> clazz, Class<?>[] parameterTypes) {
    try {//from w w w. ja  v a2  s.  co  m
        Constructor<T> ctor = clazz.getConstructor(parameterTypes);
        try {
            ctor.setAccessible(true);
        } catch (SecurityException se) {
            // do nothing
        }
        return ctor;

    } catch (NoSuchMethodException e) {
    }

    int paramSize = parameterTypes.length;
    Constructor<?>[] ctors = clazz.getDeclaredConstructors();
    for (int i = 0, size = ctors.length; i < size; i++) {
        Class<?>[] ctorParams = ctors[i].getParameterTypes();
        int ctorParamSize = ctorParams.length;
        if (ctorParamSize == paramSize) {
            boolean match = true;
            for (int n = 0; n < ctorParamSize; n++) {
                if (!MethodUtils.isAssignmentCompatible(ctorParams[n], parameterTypes[n])) {
                    match = false;
                    break;
                }
            }

            if (match) {
                Constructor<?> ctor = getDeclaredConstructor(ctors[i]);
                if (ctor != null) {
                    return (Constructor<T>) ctor;
                }
            }
        }
    }
    return null;
}

From source file:Main.java

public static Drawable showUninstallAPKIcon(Context context, String apkPath) {
    String PATH_PackageParser = "android.content.pm.PackageParser";
    String PATH_AssetManager = "android.content.res.AssetManager";
    try {/*from  ww w.  j  a va 2  s  . c  o m*/
        Class<?> pkgParserCls = Class.forName(PATH_PackageParser);
        Class<?>[] typeArgs = new Class[1];
        typeArgs[0] = String.class;
        Constructor<?> pkgParserCt = pkgParserCls.getConstructor(typeArgs);
        Object[] valueArgs = new Object[1];
        valueArgs[0] = apkPath;
        Object pkgParser = pkgParserCt.newInstance(valueArgs);
        DisplayMetrics metrics = new DisplayMetrics();
        metrics.setToDefaults();
        typeArgs = new Class[4];
        typeArgs[0] = File.class;
        typeArgs[1] = String.class;
        typeArgs[2] = DisplayMetrics.class;
        typeArgs[3] = Integer.TYPE;
        Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs);
        valueArgs = new Object[4];
        valueArgs[0] = new File(apkPath);
        valueArgs[1] = apkPath;
        valueArgs[2] = metrics;
        valueArgs[3] = 0;
        Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);
        Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");
        ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);
        Class<?> assetMagCls = Class.forName(PATH_AssetManager);
        Constructor<?> assetMagCt = assetMagCls.getConstructor((Class[]) null);
        Object assetMag = assetMagCt.newInstance((Object[]) null);
        typeArgs = new Class[1];
        typeArgs[0] = String.class;
        Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs);
        valueArgs = new Object[1];
        valueArgs[0] = apkPath;
        assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
        Resources res = context.getResources();
        typeArgs = new Class[3];
        typeArgs[0] = assetMag.getClass();
        typeArgs[1] = res.getDisplayMetrics().getClass();
        typeArgs[2] = res.getConfiguration().getClass();
        Constructor<?> resCt = Resources.class.getConstructor(typeArgs);
        valueArgs = new Object[3];
        valueArgs[0] = assetMag;
        valueArgs[1] = res.getDisplayMetrics();
        valueArgs[2] = res.getConfiguration();
        res = (Resources) resCt.newInstance(valueArgs);
        if (info.icon != 0) {
            Drawable icon = res.getDrawable(info.icon);
            return icon;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.jaeksoft.searchlib.util.ExceptionUtils.java

@SuppressWarnings("unchecked")
public static <T extends Exception> T throwException(Exception exception, Class<T> exceptionClass) throws T {
    if (exception == null)
        return null;
    if (exceptionClass.isInstance(exception))
        throw (T) exception;
    try {//from   www.  j  a va  2 s  . c  om
        return (T) exceptionClass.getConstructor(Exception.class).newInstance(exception);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.grails.datastore.mapping.reflect.ReflectionUtils.java

/**
 * Instantiates an object catching any relevant exceptions and rethrowing as a runtime exception
 *
 * @param clazz The class/*from w ww. j  av a 2 s. c o m*/
 * @return The instantiated object or null if the class parameter was null
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object instantiate(Class clazz) {
    if (clazz == null)
        return null;
    try {
        return clazz.getConstructor(EMPTY_CLASS_ARRAY).newInstance();
    } catch (IllegalAccessException e) {
        throw new InstantiationException(e.getClass().getName() + " error creating instance of class ["
                + e.getMessage() + "]: " + e.getMessage(), e);
    } catch (InvocationTargetException e) {
        throw new InstantiationException(e.getClass().getName() + " error creating instance of class ["
                + e.getMessage() + "]: " + e.getMessage(), e);
    } catch (NoSuchMethodException e) {
        throw new InstantiationException(e.getClass().getName() + " error creating instance of class ["
                + e.getMessage() + "]: " + e.getMessage(), e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException(e.getClass().getName() + " error creating instance of class ["
                + e.getMessage() + "]: " + e.getMessage(), e);
    }
}

From source file:com.salas.bb.utils.xml.XmlReaderFactory.java

/**
 * Create reader for mapped encoding. If the encoding is present in
 * <code>mapping.properties</code> then the reader will be created.
 *
 * @param is        input stream to wrap.
 * @param encoding  encoding to use.//from   w ww. j  av a  2  s .c om
 *
 * @return reader or NULL if failed or not found.
 */
static Reader createReaderForMappedEncoding(InputStream is, String encoding) {
    if (encoding == null || is == null)
        return null;

    Reader reader = null;

    String className = (String) readers.get(encoding.toLowerCase());
    if (className != null) {
        try {
            String pckg = XmlReaderFactory.class.getPackage().getName() + ".";
            Class readerClass = Class.forName(pckg + className);
            Constructor constructor = readerClass.getConstructor(new Class[] { InputStream.class });
            reader = (Reader) constructor.newInstance(new Object[] { is });
        } catch (Exception e) {
            LOG.log(Level.SEVERE, Strings.error("failed.to.initialize.reader"), e);
        }
    }

    return reader;
}

From source file:com.qualogy.qafe.business.integration.adapter.MappingAdapter.java

private static Object createServiceObj(String className, ClassLoader classLoader) {
    Object result = null;//from w  ww  .  ja  v a  2s .co  m
    try {
        if (className == null)
            throw new UnableToAdaptException("Adapter states null outputclass");

        Class<?> clazz = classLoader.loadClass(className);

        Constructor<?> c = clazz.getConstructor(new Class[0]);
        c.setAccessible(true);
        result = c.newInstance(new Object[0]);
    } catch (InstantiationException e) {
        throw new UnableToAdaptException(
                "Cannot instantiate [" + className + "], hint: define a default constructor", e);
    } catch (IllegalAccessException e) {
        throw new UnableToAdaptException(e);
    } catch (Exception e) {
        throw new UnableToAdaptException(e);
    }
    return result;
}