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:marshalsec.gadgets.ToStringUtil.java

public static Object makeJohnzonToStringTrigger(Object o) throws Exception {
    Class<?> clz = Class.forName("org.apache.johnzon.core.JsonObjectImpl"); //$NON-NLS-1$
    Constructor<?> dec = clz.getDeclaredConstructor(Map.class);
    dec.setAccessible(true);//from   w  w w  .j a  v  a2 s . c  om
    HashMap<Object, Object> m = new HashMap<>();
    Object jo = dec.newInstance(m);
    m.put(o, o);
    XString toStringTrig = new XString("");
    return Arrays.asList(jo, JDKUtil.makeMap(jo, toStringTrig));
}

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

/**
 * ??????? DTO ??//w  ww.j a v  a2s . c  o  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:edu.du.penrose.systems.fedoraApp.tasks.WorkerFactory.java

/**
 * Return the worker specified in the remote task properties file ie {institution}_{batchSet}_REMOTE.properties, if there is problem log it and return null.
 * //from ww w .  j  av a  2 s . c om
 * @see FedoraAppConstants#REMOTE_TASK_WORKER_CLASS_PROPERTY
 * 
 * @param batchSetName is of type codu_ectd where codu is the institution and ectd is the batch set name
 * @return the worker object or null.
 */
public static WorkerInf getWorker(String batchSetName) {
    String[] tempArray = batchSetName.split("_");
    String institution = tempArray[0];
    String batchSet = tempArray[1];
    WorkerInf myWorkerObject = null;
    String propertiesFileName = null;
    String workerClassName = null;

    try {
        if (batchSetName.endsWith(FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX)) {
            propertiesFileName = FedoraAppConstants.getServletContextListener().getInstituionURL().getFile()
                    + institution + "/" + batchSet + "/" + batchSet + FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX
                    + ".properties";
        } else {
            propertiesFileName = FedoraAppConstants.getServletContextListener().getInstituionURL().getFile()
                    + institution + "/" + batchSet + "/" + batchSet
                    + FedoraAppConstants.BACKGROUND_TASK_NAME_SUFFIX + ".properties";
        }

        ProgramProperties optionsProperties = new ProgramFileProperties(new File(propertiesFileName));

        if (batchSetName.endsWith(FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX)) {
            workerClassName = optionsProperties
                    .getProperty(FedoraAppConstants.REMOTE_TASK_WORKER_CLASS_PROPERTY);
        } else {
            workerClassName = optionsProperties.getProperty(FedoraAppConstants.TASK_WORKER_CLASS_PROPERTY);
        }

        if (workerClassName == null || workerClassName.length() == 0) {
            logger.error("Unable to find ingest class in" + propertiesFileName);
            return null;
        }

        Constructor<?> workerConsctuctor = Class.forName(workerClassName).getConstructor(String.class);
        myWorkerObject = (WorkerInf) workerConsctuctor.newInstance(batchSetName);
    } catch (Exception e) {
        logger.error("Unable to find ingest class for instituion_batchSet:" + institution + ", " + batchSet
                + "  :" + e.getLocalizedMessage());
        return null;
    }

    return myWorkerObject;
}

From source file:de.micromata.genome.gwiki.utils.ClassUtils.java

/**
 * //from w w w.  j av a2 s.c o m
 * @param <T>
 * @param cls
 * @param args must have the exact type
 * @return
 */
public static <T> T createInstance(Class<? extends T> cls, Class<?>[] argTypes, Object... args) {
    try {
        Constructor<? extends T> construktur = cls.getConstructor(argTypes);
        return construktur.newInstance(args);
    } catch (Throwable ex) {
        throw new RuntimeException("Cannot instantiate constructor: " + ex.getMessage(), ex);
    }
}

From source file:com.connectsdk.service.config.ServiceConfig.java

@SuppressWarnings("unchecked")
public static ServiceConfig getConfig(JSONObject json) {
    Class<ServiceConfig> newServiceClass;
    try {//from   www .java  2  s .  c o m
        newServiceClass = (Class<ServiceConfig>) Class
                .forName(ServiceConfig.class.getPackage().getName() + "." + json.optString(KEY_CLASS));
        Constructor<ServiceConfig> constructor = newServiceClass.getConstructor(JSONObject.class);

        return constructor.newInstance(json);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:TestSample.java

public static void run(Class which, String[] args) {
    TestSuite suite = null;//from  w w  w  .j ava2 s.c  om
    if (args.length != 0) {
        try {
            java.lang.reflect.Constructor ctor;
            ctor = which.getConstructor(new Class[] { String.class });
            suite = new TestSuite();
            for (int i = 0; i < args.length; i++) {
                suite.addTest((TestCase) ctor.newInstance(new Object[] { args[i] }));
            }
        } catch (Exception e) {
            System.err.println("Unable to instantiate " + which.getName() + ": " + e.getMessage());
            System.exit(1);
        }

    } else {
        try {
            Method suite_method = which.getMethod("suite", new Class[0]);
            suite = (TestSuite) suite_method.invoke(null, null);
        } catch (Exception e) {
            suite = new TestSuite(which);
        }
    }
    junit.textui.TestRunner.run(suite);
}

From source file:egovframework.rte.fdl.string.EgovObjectUtil.java

/**
 * ? ?  ?? ?? ? . ) Class <?>/*from w  ww .  ja  v a  2 s.c  o  m*/
 * clazz = EgovObjectUtil.loadClass(this.mapClass);
 * Constructor <?> constructor =
 * clazz.getConstructor(new Class
 * []{DataSource.class, String.class}); Object []
 * params = new Object []{getDataSource(),
 * getUsersByUsernameQuery()};
 * this.usersByUsernameMapping =
 * (EgovUsersByUsernameMapping)
 * constructor.newInstance(params);
 * @param className
 * @return
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws Exception
 */
public static Object instantiate(String className, String[] types, Object[] values)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, Exception {
    Class<?> clazz;
    Class<?>[] classParams = new Class[values.length];
    Object[] objectParams = new Object[values.length];

    try {
        clazz = loadClass(className);

        for (int i = 0; i < values.length; i++) {
            classParams[i] = loadClass(types[i]);
            objectParams[i] = values[i];
        }

        Constructor<?> constructor = clazz.getConstructor(classParams);
        return constructor.newInstance(values);

    } catch (ClassNotFoundException e) {
        if (log.isErrorEnabled())
            log.error(className + " : Class is can not instantialized.");
        throw new ClassNotFoundException();
    } catch (InstantiationException e) {
        if (log.isErrorEnabled())
            log.error(className + " : Class is can not instantialized.");
        throw new InstantiationException();
    } catch (IllegalAccessException e) {
        if (log.isErrorEnabled())
            log.error(className + " : Class is not accessed.");
        throw new IllegalAccessException();
    } catch (Exception e) {
        if (log.isErrorEnabled())
            log.error(className + " : Class is not accessed.");
        throw new Exception(e);
    }
}

From source file:com.mobilyzer.util.MeasurementJsonConvertor.java

public static MeasurementTask makeMeasurementTaskFromJson(JSONObject json) throws IllegalArgumentException {
    try {/*from w w  w .ja  v  a 2 s .c o  m*/
        String type = String.valueOf(json.getString("type"));
        Class taskClass = MeasurementTask.getTaskClassForMeasurement(type);
        Method getDescMethod = taskClass.getMethod("getDescClass");
        // The getDescClassForMeasurement() is static and takes no arguments
        Class descClass = (Class) getDescMethod.invoke(null, (Object[]) null);
        MeasurementDesc measurementDesc = (MeasurementDesc) gson.fromJson(json.toString(), descClass);

        Object cstParam = measurementDesc;
        Constructor<MeasurementTask> constructor = taskClass.getConstructor(MeasurementDesc.class);
        return constructor.newInstance(cstParam);
    } catch (JSONException e) {
        throw new IllegalArgumentException(e);
    } catch (SecurityException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (NoSuchMethodException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalArgumentException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InstantiationException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InvocationTargetException e) {
        Logger.w(e.toString());
        throw new IllegalArgumentException(e);
    }
}

From source file:com.google.gdt.eclipse.designer.mac.BrowserShellMacImplCocoa.java

private static Image createImageFromHandle(long imageHandle, int width, int height) throws Exception {
    if (imageHandle != 0) {
        Class<?> nsImageClass = Class.forName("org.eclipse.swt.internal.cocoa.NSImage");
        Object handleObject;//from   w ww. j ava2 s .  c om
        Class<?> handleClass;
        if (SystemUtils.OS_ARCH.indexOf("64") != -1) {
            handleClass = long.class;
            handleObject = new Long(imageHandle);
        } else {
            handleClass = int.class;
            handleObject = new Integer((int) imageHandle);
        }
        Constructor<?> constructor = nsImageClass.getConstructor(handleClass);
        Object nsImage = constructor.newInstance(handleObject);
        // Create a temporary image using the captured image's handle
        Class<?> NSImageClass = Class.forName("org.eclipse.swt.internal.cocoa.NSImage");
        Method method = Image.class.getDeclaredMethod("cocoa_new",
                new Class[] { Device.class, int.class, NSImageClass });
        method.setAccessible(true);
        Image tempImage = (Image) method.invoke(null,
                new Object[] { Display.getCurrent(), new Integer(SWT.BITMAP), nsImage });
        // Create the result image
        Image image = new Image(Display.getCurrent(), width, height);
        // Manually copy because the image's data handle isn't available
        GC gc = new GC(tempImage);
        gc.copyArea(image, 0, 0);
        gc.dispose();
        // Dispose of the temporary image allocated in the native call
        tempImage.dispose();
        return image;
    }
    // prevent failing
    return new Image(Display.getCurrent(), 1, 1);
}

From source file:com.github.dryangkun.hbase.tidx.hive.HBaseTableSnapshotInputFormatUtil.java

/**
 * Create a bare TableSnapshotRegionSplit. Needed because Writables require a
 * default-constructed instance to hydrate from the DataInput.
 *
 * TODO: remove once HBASE-11555 is fixed.
 *//*from  www .j ava2  s .co m*/
public static InputSplit createTableSnapshotRegionSplit() {
    try {
        assertSupportsTableSnapshots();
    } catch (RuntimeException e) {
        LOG.debug("Probably don't support table snapshots. Returning null instance.", e);
        return null;
    }

    try {
        Class<? extends InputSplit> resultType = (Class<? extends InputSplit>) Class
                .forName(TABLESNAPSHOTREGIONSPLIT_CLASS);
        Constructor<? extends InputSplit> cxtor = resultType.getDeclaredConstructor(new Class[] {});
        cxtor.setAccessible(true);
        return cxtor.newInstance(new Object[] {});
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Unable to find " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (IllegalAccessException e) {
        throw new UnsupportedOperationException(
                "Unable to access specified class " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (InstantiationException e) {
        throw new UnsupportedOperationException(
                "Unable to instantiate specified class " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (InvocationTargetException e) {
        throw new UnsupportedOperationException(
                "Constructor threw an exception for " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (NoSuchMethodException e) {
        throw new UnsupportedOperationException(
                "Unable to find suitable constructor for class " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    }
}