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:libepg.epg.section.sdt.ClassGetter.java

public static ServiceDescriptionTableRepeatingPart init(byte[] data) throws Throwable {
    try {/*from  w w  w. j  av  a  2s  .  c  o m*/
        Object[] args = { data };
        Class<?>[] params = { byte[].class };
        Constructor<ServiceDescriptionTableRepeatingPart> constructor = ServiceDescriptionTableRepeatingPart.class
                .getDeclaredConstructor(params);
        constructor.setAccessible(true);
        ServiceDescriptionTableRepeatingPart target = constructor.newInstance(args);
        return target;
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | SecurityException ex) {
        LOG.fatal(ex);
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
    return null;
}

From source file:info.magnolia.module.admininterface.dialogs.ConfiguredDialog.java

/**
 * @param paragraph//from  w w w .ja  v  a2  s  . c  om
 * @param configNode2
 * @param request
 * @param response
 * @param class1
 * @return
 */
public static ConfiguredDialog getConfiguredDialog(String name, Content configNode, HttpServletRequest request,
        HttpServletResponse response, Class defaultClass) {
    // get class name
    String className = null;
    try {
        Class handlerClass = defaultClass;
        try {
            className = configNode.getNodeData("class").getString(); //$NON-NLS-1$
            if (StringUtils.isNotEmpty(className)) {
                handlerClass = Class.forName(className);
            }
        } catch (Exception e) {
            log.error(MessageFormat.format("Unable to load class {0}", new Object[] { className })); //$NON-NLS-1$
        }
        Constructor constructor = handlerClass.getConstructor(new Class[] { String.class,
                HttpServletRequest.class, HttpServletResponse.class, Content.class });
        return (ConfiguredDialog) constructor.newInstance(new Object[] { name, request, response, configNode });
    } catch (Exception e) {
        log.error("can't instantiate dialog: ", e); //$NON-NLS-1$
        return null;
    }
}

From source file:com.opengamma.util.ReflectionUtils.java

/**
 * Creates an instance of a class from a constructor.
 * /*from w w  w  .j a  v a 2s. co  m*/
 * @param <T> the type
 * @param constructor  the constructor to call, not null
 * @param args  the arguments, not null
 * @return the constructor, not null
 * @throws RuntimeException if the class cannot be loaded
 */
public static <T> T newInstance(final Constructor<T> constructor, final Object... args) {
    try {
        return constructor.newInstance(args);
    } catch (InstantiationException ex) {
        throw new OpenGammaRuntimeException(ex.getMessage(), ex);
    } catch (IllegalAccessException ex) {
        throw new OpenGammaRuntimeException(ex.getMessage(), ex);
    } catch (InvocationTargetException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            throw (RuntimeException) ex.getCause();
        }
        throw new OpenGammaRuntimeException(ex.getMessage(), ex);
    }
}

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 w w . j  a v  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:libepg.common.descriptor.Descriptors.java

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

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

private static Object createServiceObj(String className, ClassLoader classLoader) {
    Object result = null;//from   ww w .j a  va  2 s .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;
}

From source file:Main.java

public static void setDUMode() {
    System.err.println("Orion::setDUMode");
    try {//from  www . ja v a2  s  .co m
        if (successful) {
            Constructor RegionParamsConstructor = epdControllerRegionParamsClass
                    .getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE,
                            epdControllerWaveClass, Integer.TYPE });

            Object localRegionParams = RegionParamsConstructor
                    .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[2], 14 });

            Method epdControllerSetRegionMethod = epdControllerClass.getMethod("setRegion",
                    new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass });
            epdControllerSetRegionMethod.invoke(null,
                    new Object[] { "Orion", regionEnums[2], localRegionParams });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.hawk.service.api.utils.APIUtils.java

@SuppressWarnings({ "deprecation", "restriction" })
public static <T extends TServiceClient> T connectTo(Class<T> clazz, String url, ThriftProtocol thriftProtocol,
        final Credentials credentials) throws TTransportException, URISyntaxException {
    try {//w ww  .ja  v a2  s .co  m
        final URI parsed = new URI(url);

        TTransport transport;
        if (parsed.getScheme().startsWith("http")) {
            final DefaultHttpClient httpClient = APIUtils.createGZipAwareHttpClient();
            if (credentials != null) {
                httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), credentials);
            }
            transport = new THttpClient(url, httpClient);
        } else {
            transport = new TZlibTransport(new TSocket(parsed.getHost(), parsed.getPort()));
            transport.open();
        }
        Constructor<T> constructor = clazz.getDeclaredConstructor(org.apache.thrift.protocol.TProtocol.class);
        return constructor.newInstance(thriftProtocol.getProtocolFactory().getProtocol(transport));
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new TTransportException(e);
    }
}

From source file:com.chiorichan.factory.groovy.GroovyRegistry.java

public static Script getCachedScript(ScriptingContext context, Binding binding) {
    try {/*ww w.j  ava  2  s  .c om*/
        // File classFile = FileFunc.buildFile( context.cache(), context.scriptPackage().replace( '.', File.separatorChar ), context.scriptSimpleName() + ".class" );
        if (scriptCacheMd5.containsKey(context.scriptClassName())) {
            if (scriptCacheMd5.get(context.site().getId() + "//" + context.scriptClassName())
                    .equals(context.md5())) {
                Class<?> scriptClass = Class.forName(context.scriptClassName());
                Constructor<?> con = scriptClass.getConstructor(Binding.class);
                Script script = (Script) con.newInstance(binding);
                return script;
            }
        } else
            scriptCacheMd5.put(context.site().getId() + "//" + context.scriptClassName(), context.md5());
    } catch (Throwable t) {

    }
    return null;
}

From source file:com.glaf.jbpm.util.CustomFieldInstantiator.java

public static Object getValue(Class<?> type, Element propertyElement) {
    Object value = null;//from   ww w  .j  a  v  a2  s.  c  om
    if (type == String.class) {
        value = propertyElement.getText();
    } else if ((type == Integer.class) || (type == int.class)) {
        value = Integer.parseInt(propertyElement.getTextTrim());
    } else if ((type == Long.class) || (type == long.class)) {
        value = Long.parseLong(propertyElement.getTextTrim());
    } else if ((type == Float.class) || (type == float.class)) {
        value = new Float(propertyElement.getTextTrim());
    } else if ((type == Double.class) || (type == double.class)) {
        value = Double.parseDouble(propertyElement.getTextTrim());
    } else if ((type == Boolean.class) || (type == boolean.class)) {
        value = Boolean.valueOf(propertyElement.getTextTrim());
    } else if ((type == Character.class) || (type == char.class)) {
        value = Character.valueOf(propertyElement.getTextTrim().charAt(0));
    } else if ((type == Short.class) || (type == short.class)) {
        value = Short.valueOf(propertyElement.getTextTrim());
    } else if ((type == Byte.class) || (type == byte.class)) {
        value = Byte.valueOf(propertyElement.getTextTrim());
    } else if (type.isAssignableFrom(java.util.Date.class)) {
        value = DateUtils.toDate(propertyElement.getTextTrim());
    } else if (type.isAssignableFrom(List.class)) {
        value = getCollectionValue(propertyElement, new java.util.ArrayList<Object>());
    } else if (type.isAssignableFrom(Set.class)) {
        value = getCollectionValue(propertyElement, new LinkedHashSet<Object>());
    } else if (type.isAssignableFrom(Collection.class)) {
        value = getCollectionValue(propertyElement, new java.util.ArrayList<Object>());
    } else if (type.isAssignableFrom(Map.class)) {
        value = getMapValue(propertyElement, new LinkedHashMap<Object, Object>());
    } else if (type == Element.class) {
        value = propertyElement;
    } else {
        try {
            Constructor<?> constructor = type.getConstructor(new Class[] { String.class });
            if ((propertyElement.isTextOnly()) && (constructor != null)) {
                value = constructor.newInstance(new Object[] { propertyElement.getTextTrim() });
            }
        } catch (Exception ex) {
            logger.error("couldn't parse the bean property value '" + propertyElement.asXML() + "' to a '"
                    + type.getName() + "'");
            throw new RuntimeException(ex);
        }
    }

    return value;
}