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:edu.umn.msi.tropix.common.reflect.ReflectionHelperImpl.java

public <T> T newInstance(final Class<T> clazz, final Class<?>[] constructorArgTypes,
        final Object[] constructorArgs) {
    final Constructor<T> constructor = getConstructor(clazz, constructorArgTypes);
    T instance = null;/*www  .j  a va 2  s  .co  m*/
    try {
        instance = constructor.newInstance(constructorArgs);
    } catch (final Exception e) {
        throw new ReflectionRuntimeException(e);
    }
    return instance;
}

From source file:com.cloudera.sqoop.manager.DefaultManagerFactory.java

public ConnManager accept(JobData data) {
    SqoopOptions options = data.getSqoopOptions();
    String manualDriver = options.getDriverClassName();
    if (manualDriver != null) {
        // User has manually specified JDBC implementation with --driver.
        // Just use GenericJdbcManager.
        return new GenericJdbcManager(manualDriver, options);
    }/*from   w  w w. j  a v a2  s  .  co  m*/

    if (null != options.getConnManagerClassName()) {
        String className = options.getConnManagerClassName();
        ConnManager connManager = null;
        try {
            Class<ConnManager> cls = (Class<ConnManager>) Class.forName(className);
            Constructor<ConnManager> constructor = cls.getDeclaredConstructor(SqoopOptions.class);
            connManager = constructor.newInstance(options);
        } catch (Exception e) {
            System.err.println("problem finding the connection manager for class name :" + className);
            // Log the stack trace for this exception
            LOG.debug(e.getMessage(), e);
            // Print exception message.
            System.err.println(e.getMessage());
        }
        return connManager;
    }

    String connectStr = options.getConnectString();

    // java.net.URL follows RFC-2396 literally, which does not allow a ':'
    // character in the scheme component (section 3.1). JDBC connect strings,
    // however, commonly have a multi-scheme addressing system. e.g.,
    // jdbc:mysql://...; so we cannot parse the scheme component via URL
    // objects. Instead, attempt to pull out the scheme as best as we can.

    // First, see if this is of the form [scheme://hostname-and-etc..]
    int schemeStopIdx = connectStr.indexOf("//");
    if (-1 == schemeStopIdx) {
        // If no hostname start marker ("//"), then look for the right-most ':'
        // character.
        schemeStopIdx = connectStr.lastIndexOf(':');
        if (-1 == schemeStopIdx) {
            // Warn that this is nonstandard. But we should be as permissive
            // as possible here and let the ConnectionManagers themselves throw
            // out the connect string if it doesn't make sense to them.
            LOG.warn("Could not determine scheme component of connect string");

            // Use the whole string.
            schemeStopIdx = connectStr.length();
        }
    }

    String scheme = connectStr.substring(0, schemeStopIdx);

    if (null == scheme) {
        // We don't know if this is a mysql://, hsql://, etc.
        // Can't do anything with this.
        LOG.warn("Null scheme associated with connect string.");
        return null;
    }

    LOG.debug("Trying with scheme: " + scheme);

    if (scheme.equals("jdbc:mysql:")) {
        if (options.isDirect()) {
            return new DirectMySQLManager(options);
        } else {
            return new MySQLManager(options);
        }
    } else if (scheme.equals("jdbc:postgresql:")) {
        if (options.isDirect()) {
            return new DirectPostgresqlManager(options);
        } else {
            return new PostgresqlManager(options);
        }
    } else if (scheme.startsWith("jdbc:hsqldb:")) {
        return new HsqldbManager(options);
    } else if (scheme.startsWith("jdbc:oracle:")) {
        return new OracleManager(options);
    } else {
        return null;
    }
}

From source file:com.strider.datadefender.requirement.Parameter.java

private Object getTypeValueOf(final String type, final String value) throws ClassNotFoundException,
        NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    if (type.equals(boolean.class.getName())) {
        return Boolean.parseBoolean(value);
    } else if (type.equals(byte.class.getName())) {
        return Byte.parseByte(value);
    } else if (type.equals(short.class.getName())) {
        return Short.parseShort(value);
    } else if (type.equals(char.class.getName())) {
        return value.charAt(0);
    } else if (type.equals(int.class.getName())) {
        return Integer.parseInt(value);
    } else if (type.equals(long.class.getName())) {
        return Long.parseLong(value);
    } else if (type.equals(float.class.getName())) {
        return Float.parseFloat(value);
    } else if (type.equals(double.class.getName())) {
        return Double.parseDouble(value);
    } else if (type.equals(String.class.getName()) || "String".equals(type)) {
        return value;
    } else {/*from  ww w  .  j  ava 2s  . c  om*/
        final Constructor<?> constr = Class.forName(type).getConstructor(String.class);

        return constr.newInstance(value);
    }
}

From source file:com.swordlord.gozer.ui.gozerframe.GozerFrameLink.java

@Override
public void onClick() {
    IGozerFrameExtension gfe = null;/*from w w  w. j  a  v a  2s . c o  m*/

    try {
        Class<? extends IGozerFrameExtension> clazz = getGozerFrameExtension();
        Constructor<? extends IGozerFrameExtension> c = clazz
                .getConstructor(new Class[] { IGozerSessionInfo.class });
        gfe = c.newInstance(new Object[] { _sessionInfo });
    } catch (InvocationTargetException e) {
        LOG.error(e.getCause());
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        LOG.error(e.getCause());
        e.printStackTrace();
    } catch (InstantiationException e) {
        LOG.error(e.getCause());
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        LOG.error(e.getCause());
        e.printStackTrace();
    } catch (SecurityException e) {
        LOG.error(e.getCause());
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        LOG.error(e.getCause());
        e.printStackTrace();
    }

    GozerPage page = null;

    if (_clazz != null) {
        page = GozerPage.getFrame(gfe, _clazz);
    } else {
        page = GozerPage.getFrame(gfe);
    }

    if (page != null) {
        setResponsePage(page);
    } else {
        LOG.error("GozerFile does not exist, is null or empty: " + gfe.getGozerLayoutFileName());
    }
}

From source file:com.mgmtp.perfload.agent.TransformerTest.java

@Test
public void testMeasuringHook() throws Exception {
    Constructor<?> constructor = testClass.getConstructor(Boolean.class);

    Object object = constructor.newInstance(Boolean.TRUE);
    try {//  ww  w.j av a 2s .c  o  m
        object.getClass().getMethod("check").invoke(object);
        fail();
    } catch (InvocationTargetException ex) {
        // expected
    }

    object = constructor.newInstance(Boolean.FALSE);
    testClass.getMethod("checkI", int.class).invoke(null, 1);
    testClass.getMethod("checkLL", long.class, long.class).invoke(object, 42L, 43L);
    testClass.getMethod("check").invoke(object);

    List<String> measuringLogContents = Files.readLines(MEASURING_LOG_FILE, Charsets.UTF_8);
    assertEquals(measuringLogContents.size(), 4);
    assertTrue(measuringLogContents.get(0).contains("ERROR"));
    assertTrue(measuringLogContents.get(1).contains("SUCCESS"));
    assertTrue(measuringLogContents.get(2).contains("SUCCESS"));
    assertTrue(measuringLogContents.get(3).contains("SUCCESS"));
}

From source file:info.novatec.testit.livingdoc.runner.DocumentRunner.java

private InterpreterSelector newInterpreterSelector(SystemUnderDevelopment sud)
        throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    Constructor<? extends InterpreterSelector> constructor = interpreterSelectorClass
            .getConstructor(SystemUnderDevelopment.class);
    return constructor.newInstance(sud);
}

From source file:com.legstar.proxy.invoke.ServiceProxy.java

/**
 * Load the operation proxy named in the configuration or the default one
 * if none is found./*from w w w .  j  av  a2  s. c  o  m*/
 * 
 * @param config the current configuration
 * @return an instance of the operation proxy
 * @throws ProxyConfigurationException if unable to instantiate the
 *             operation proxy
 */
private IOperationProxy getOperationProxy(final Map<String, String> config) throws ProxyConfigurationException {
    try {
        String operationProxyClassName = config.get(OPERATION_PROXY_CLASS_NAME_PROPERTY);
        if (operationProxyClassName == null || operationProxyClassName.length() == 0) {
            operationProxyClassName = DEFAULT_OPERATION_PROXY_CLASS_NAME;
        }
        Class<?> clazz = ClassUtil.loadClass(operationProxyClassName);
        Constructor<?> constructor = clazz.getConstructor(Map.class);
        return (IOperationProxy) constructor.newInstance(new Object[] { config });
    } catch (SecurityException e) {
        throw new ProxyConfigurationException(e);
    } catch (IllegalArgumentException e) {
        throw new ProxyConfigurationException(e);
    } catch (ClassNotFoundException e) {
        throw new ProxyConfigurationException(e);
    } catch (NoSuchMethodException e) {
        throw new ProxyConfigurationException(e);
    } catch (InstantiationException e) {
        throw new ProxyConfigurationException(e);
    } catch (IllegalAccessException e) {
        throw new ProxyConfigurationException(e);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof ProxyConfigurationException) {
            throw (ProxyConfigurationException) e.getTargetException();
        }
        throw new ProxyConfigurationException(e);
    }
}

From source file:com.uwsoft.editor.view.ui.box.resourcespanel.UIAnimationsTabMediator.java

private void createAnimationResources(Set<String> strings, Class resourceClass,
        BiFunction<String, Vector2, Boolean> factoryFunction, String searchText) {
    for (String animationName : strings) {
        if (!animationName.contains(searchText))
            continue;
        try {//from  w  w w  .  j  a v a  2  s .  c o  m
            Constructor constructor = resourceClass.getConstructor(String.class);
            DraggableResource draggableResource = new DraggableResource(
                    (DraggableResourceView) constructor.newInstance(animationName));
            draggableResource.initDragDrop();
            draggableResource.setFactoryFunction(factoryFunction);
            animationBoxes.add(draggableResource);
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:libepg.epg.section.descriptor.DescriptorsLoop.java

/**
 * ????//from   w  w  w.  j  a  v a2 s . co  m
 * ???????????????????????
 *
 * @return ?
 */
public synchronized List<Descriptor> getDescriptors_loopList() {
    List<byte[]> t = ByteArraySplitter.splitByLengthField(this.getData(), 2, 1);
    List<Descriptor> dest = new ArrayList<>();
    for (byte[] temp : t) {
        Descriptor desc = new Descriptor(temp);

        Descriptor target = null;
        try {
            Object[] args = { desc };
            Class<?>[] params = { Descriptor.class };
            Constructor<? extends Descriptor> constructor = desc.getDescriptor_tag_const().getDataType()
                    .getDeclaredConstructor(params);
            target = constructor.newInstance(args);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
            LOG.fatal("???????????? = "
                    + desc.toString(), ex);
            target = desc;
        } finally {
            dest.add(target);
        }

    }
    return Collections.unmodifiableList(dest);
}

From source file:com.w20e.socrates.workflow.ActionFactory.java

/**
 * Create a new ProcessAction.//from w  w w. j  a  v a 2  s  .c  om
 * 
 * @param attrs
 *            the attributes on this element.
 * @return an new ProcessAction
 * @exception Exception
 *                if the action has no class attribute or no id attribute.
 */
public final Object createObject(final Attributes attrs) throws Exception {

    if (actions.containsKey(attrs.getValue("idref"))) {
        return ActionFactory.getAction(attrs.getValue("idref"));
    }

    if (attrs.getValue("class") == null || attrs.getValue("id") == null || "".equals(attrs.getValue("class"))
            || "".equals(attrs.getValue("id"))) {
        throw new Exception("No class or id specified!");
    }

    final Class<?>[] args = { Class.forName(String.class.getName()) };

    final Constructor<?> constr = Class.forName(attrs.getValue("class")).getConstructor(args);

    final Object[] objArgs = { attrs.getValue("id") };

    final ProcessAction action = (ProcessAction) constr.newInstance(objArgs);

    actions.put(action.getId(), action);

    return action;
}