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.xpn.xwiki.plugin.charts.plots.LinePlotFactory.java

public Plot create(DataSource dataSource, ChartParams params) throws GenerateException, DataSourceException {
    Class rendererClass = params.getClass(ChartParams.RENDERER);
    if (rendererClass == null || XYItemRenderer.class.isAssignableFrom(rendererClass)) {
        XYItemRenderer renderer;/*from  w  ww.j a v  a 2  s.c o  m*/
        if (rendererClass != null) {
            try {
                Constructor ctor = rendererClass.getConstructor(new Class[] {});
                renderer = (XYItemRenderer) ctor.newInstance(new Object[] {});
            } catch (Throwable e) {
                throw new GenerateException(e);
            }
        } else {
            renderer = new XYLineAndShapeRenderer();
        }
        ChartCustomizer.customizeXYItemRenderer(renderer, params);

        return XYPlotFactory.getInstance().create(dataSource, renderer, params);
    } else if (CategoryItemRenderer.class.isAssignableFrom(rendererClass)) {
        CategoryItemRenderer renderer;
        if (rendererClass != null) {
            try {
                Constructor ctor = rendererClass.getConstructor(new Class[] {});
                renderer = (CategoryItemRenderer) ctor.newInstance(new Object[] {});
            } catch (Throwable e) {
                throw new GenerateException(e);
            }
        } else {
            renderer = new LineAndShapeRenderer();
        }
        ChartCustomizer.customizeCategoryItemRenderer(renderer, params);

        return CategoryPlotFactory.getInstance().create(dataSource, renderer, params);
    } else {
        throw new GenerateException("Incompatible renderer class: " + rendererClass);
    }
}

From source file:com.konakart.apiexamples.BaseApiExample.java

/**
 * Utility method to instantiate an engine instance. The class name of the engine is passed in
 * as a parameter so this method may be used to instantiate a POJO engine, a SOAP engine, an RMI
 * engine or a JSON engine./*from w  w w .j a  va2  s .c o m*/
 * 
 * @param engineClassName
 * @param config
 * @return Returns an Engine Instance
 * @throws IllegalArgumentException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 */
protected static KKEngIf getKKEngByName(String engineClassName, EngineConfig config)
        throws IllegalArgumentException, InstantiationException, IllegalAccessException,
        InvocationTargetException, ClassNotFoundException {
    Class<?> engineClass = Class.forName(engineClassName);
    KKEngIf kkeng = null;
    Constructor<?>[] constructors = engineClass.getConstructors();
    Constructor<?> engConstructor = null;
    if (constructors != null && constructors.length > 0) {
        for (int i = 0; i < constructors.length; i++) {
            Constructor<?> constructor = constructors[i];
            Class<?>[] parmTypes = constructor.getParameterTypes();
            if (parmTypes != null && parmTypes.length == 1) {
                String parmName = parmTypes[0].getName();
                if (parmName != null && parmName.equals("com.konakart.appif.EngineConfigIf")) {
                    engConstructor = constructor;
                }
            }
        }
    }

    if (engConstructor != null) {
        kkeng = (KKEngIf) engConstructor.newInstance(config);
    }

    return kkeng;
}

From source file:com.voa.weixin.mission.MissionManager.java

private void init() {
    Document doc = null;//from   www . ja va 2 s.  c o  m
    try {
        doc = WeixinUtils.getDocumentResource("weixin.mission.xml");

    } catch (Exception e) {
        logger.warn("can't find or parser weixin.mission.xml:" + e.getMessage());
    }
    if (doc == null)
        return;

    List<Element> missionEs = doc.getRootElement().elements("mission");

    for (Element missionE : missionEs) {
        String name = missionE.elementText("name");
        String period = missionE.elementText("period");
        String delay = missionE.elementText("delay");
        String className = missionE.elementText("class");

        try {
            Class clz = Class.forName(className);
            Constructor<Mission> constructor = clz.getConstructor(String.class);

            Mission mission = constructor.newInstance(name);

            mission.setDelay((Integer.valueOf(delay) * 1000));
            mission.setPeriod((Integer.valueOf(period) * 1000));

            missions.put(name, mission);

            timer.schedule(mission, mission.getDelay(), mission.getPeriod());
        } catch (Exception e) {
            logger.warn("mission can't be instance : " + name);
            logger.warn("cause by " + e.getMessage());
        }
    }

}

From source file:ch.cyberduck.core.LocalFactory.java

protected Local create(final String path) {
    final String clazz = PreferencesFactory.get().getProperty("factory.local.class");
    if (null == clazz) {
        throw new FactoryException(
                String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
    }/*from  w  w w.  j a v a 2  s  .c o m*/
    try {
        final Class<Local> name = (Class<Local>) Class.forName(clazz);
        final Constructor<Local> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
                path.getClass());
        return constructor.newInstance(path);
    } catch (InstantiationException | InvocationTargetException | ClassNotFoundException
            | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}

From source file:com.meidusa.amoeba.net.packet.AbstractPacket.java

private T constractorBuffer(byte[] buffer) {
    T packetbuffer = null;//from w ww. j ava2 s .com
    try {
        Constructor<T> constractor = getPacketBufferClass().getConstructor(byte[].class);
        packetbuffer = constractor.newInstance(buffer);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return packetbuffer;
}

From source file:ips1ap101.lib.core.util.ClassX.java

public synchronized Object newInstance(Class<?> baseClass, String subclassName,
        TypeValuePair... typeValuePairs) {
    Bitacora.trace(ClassX.class, "newInstance", baseClass, subclassName);
    if (baseClass == null) {
        throw new IllegalArgumentException();
    }// w  w w.  ja  va 2  s .c o  m
    Class<?> classX = getClassX(baseClass, subclassName);
    try {
        if (typeValuePairs == null || typeValuePairs.length == 0) {
            return classX.newInstance();
        }
        Class<?>[] parameterTypes = getTypes(typeValuePairs);
        Object[] initargs = getValues(typeValuePairs);
        Constructor<?> constructor = classX.getConstructor(parameterTypes);
        return constructor.newInstance(initargs);
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
            | IllegalArgumentException | InvocationTargetException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jboss.arquillian.spring.integration.inject.container.XmlRemoteApplicationContextProducer.java

/**
 * <p>Creates new instance of {@link org.springframework.context.ApplicationContext}.</p>
 *
 * @param applicationContextClass the class of application context
 * @param locations               the locations from which load the configuration files
 *
 * @return the created {@link org.springframework.context.ApplicationContext} instance
 *///from  w w w . j a va  2s .  c o  m
private <T extends ApplicationContext> ApplicationContext createInstance(Class<T> applicationContextClass,
        String[] locations) {

    try {
        Constructor<T> ctor = applicationContextClass.getConstructor(String[].class);

        return ctor.newInstance((Object) locations);
    } catch (NoSuchMethodException e) {

        throw new RuntimeException("Could not create instance of " + applicationContextClass.getName()
                + ", no appropriate constructor found.", e);
    } catch (InvocationTargetException e) {

        throw new RuntimeException("Could not create instance of " + applicationContextClass.getName(), e);
    } catch (InstantiationException e) {

        throw new RuntimeException("Could not create instance of " + applicationContextClass.getName(), e);
    } catch (IllegalAccessException e) {

        throw new RuntimeException("Could not create instance of " + applicationContextClass.getName(), e);
    }
}

From source file:com.isencia.passerelle.message.type.ComplexConverter.java

protected Object convertContentToType(Object content, Class targetType)
        throws UnsupportedOperationException, MessageException {
    if (targetType != null && !Complex.class.equals(targetType)) {
        // do a conversion via a String representation
        try {//from  w w w .java  2 s .  c om
            Constructor c = targetType.getConstructor(new Class[] { String.class });
            return c.newInstance(new Object[] { content.toString() });
        } catch (Exception e) {
            throw new UnsupportedOperationException();
        }
    } else {
        // do a conversion to Complex via a String representation
        String contentStr = content.toString();
        try {
            org.apache.commons.math.complex.Complex complex = null;
            try {
                complex = iFormat.parse(contentStr);
            } catch (ParseException e) {
                // Try the j-format
                complex = jFormat.parse(contentStr);
            }
            return new Complex(complex.getReal(), complex.getImaginary());
        } catch (ParseException e) {
            throw new MessageException(ErrorCode.MSG_CONTENT_TYPE_ERROR, "Error converting " + content, e);
        }
    }
}

From source file:net.gplatform.sudoor.server.security.model.filter.CustomizeRequestFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    logger.debug("CustomizeRequestFilter Start to Customize");
    logger.debug("Original request -> {}", request);

    ServletRequest newRequestObject = null;
    try {//from  w  w w .j  a v  a 2 s . c o  m
        Class newRequestClass = Class.forName(requestFullName);
        Constructor newRequestConstructor = newRequestClass.getConstructor(HttpServletRequest.class);
        newRequestObject = (ServletRequest) newRequestConstructor.newInstance(request);
    } catch (Exception e) {
        logger.error("Can not customize request", e);
    }

    if (newRequestObject == null) {
        logger.debug("Execute Chain with original request");
        chain.doFilter(request, response);
    } else {
        logger.debug("Execute Chain with new request -> {}", newRequestObject);
        chain.doFilter(newRequestObject, response);
    }

}

From source file:net.dmulloy2.ultimatearena.api.SimpleArenaType.java

@Override
public Arena newArena(ArenaZone az) {
    Class<? extends Arena> clazz = getArena();
    Validate.notNull(clazz, "Arena class cannot be null!");

    try {/*from w  w w  .jav  a  2s .  com*/
        Constructor<? extends Arena> constructor = clazz.getConstructor(ArenaZone.class);
        return constructor.newInstance(az);
    } catch (InvocationTargetException ex) {
        throw new RuntimeException("Failed to create new " + clazz.getName() + " instance.", ex);
    } catch (Throwable ex) {
        throw Throwables.propagate(ex);
    }
}