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:de.openknowledge.domain.SimpleValueObjectBuilder.java

private SimpleValueObjectBuilder(Class<V> valueObjectClass) {
    ParameterizedType valueObjectSuperclass = (ParameterizedType) valueObjectClass.getGenericSuperclass();
    Class<?> simpleClass = (Class<?>) valueObjectSuperclass.getActualTypeArguments()[0];
    try {//  www  .  j a  va2 s.c om
        valueObjectConstructor = valueObjectClass.getConstructor(simpleClass);
    } catch (NoSuchMethodException ex) {
        if (ClassUtils.isPrimitiveWrapper(simpleClass)) {
            try {
                valueObjectConstructor = valueObjectClass
                        .getConstructor(ClassUtils.wrapperToPrimitive(simpleClass));
            } catch (NoSuchMethodException e) {
                throw new IllegalStateException("Value Object " + valueObjectClass.getName() + " requires "
                        + simpleClass.getSimpleName() + "-Constructor to be used with Converter/Adapter");
            }
        } else {
            throw new IllegalStateException("Value Object " + valueObjectClass.getName() + " requires "
                    + simpleClass.getSimpleName() + "-Constructor to be used with Converter/Adapter");
        }
    }
    if (simpleClass.isPrimitive()) {
        simpleClass = ClassUtils.primitiveToWrapper(simpleClass);
    }
    try {
        simpleValueConstructor = simpleClass.getConstructor(String.class);
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException("Value Object simple type " + simpleClass.getName()
                + " requires String-Constructor to be used with JSF Converter");
    }
}

From source file:it.geosolutions.geobatch.annotations.GenericActionService.java

/**
 * Istantiate an action class from the Class type and the ActionConfig provided.
  * <p/>/*w w w  .j  a v a  2 s . c om*/
  * Once the class is instantiated: <ol>
  * <li>{@code @autowire} fields are autowired</li>
  * <li>{@code afterPropertiesSet()} is called if {@code InitializingBean} is declared</li>
  * </ol>
 * @param actionClass
 * @param actionConfig
 * @return
 */
public <T extends BaseAction<? extends EventObject>> T createAction(Class<T> actionClass,
        ActionConfiguration actionConfig) {

    try {
        LOGGER.info("Instantiating action " + actionClass.getSimpleName());
        Constructor<T> constructor = actionClass.getConstructor(actionConfig.getClass());
        T newInstance = constructor.newInstance(actionConfig);

        ((AbstractRefreshableApplicationContext) applicationContext).getBeanFactory().autowireBean(newInstance);
        if (InitializingBean.class.isAssignableFrom(actionClass)) {
            ((InitializingBean) newInstance).afterPropertiesSet();
        }

        return newInstance;
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
        throw new IllegalStateException("A fatal error occurred while instantiate the action class "
                + actionClass.getSimpleName() + ": " + e.getLocalizedMessage());
    }
}

From source file:com.netspective.sparx.navigate.NavigationTrees.java

public NavigationTree createNavigationTree(Class cls) throws NoSuchMethodException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    if (NavigationTree.class.isAssignableFrom(cls)) {
        Constructor c = cls.getConstructor(new Class[] { Project.class });
        return (NavigationTree) c.newInstance(new Object[] { project });
    } else/* www. j a  v a  2s  .c o  m*/
        throw new RuntimeException("Don't know what to do with with class: " + cls);
}

From source file:info.magnolia.module.admininterface.PageHandlerManager.java

/**
 * Find a handler by name// w ww .  j a  va  2s. c om
 * @param name
 * @param request
 * @param response
 * @returnn an instance of the handlers
 */
public PageMVCHandler getPageHandler(String name, HttpServletRequest request, HttpServletResponse response) {

    Class dialogPageHandlerClass = (Class) dialogPageHandlers.get(name);
    if (dialogPageHandlerClass == null) {
        throw new InvalidDialogPageHandlerException(name);
    }

    try {
        Constructor constructor = dialogPageHandlerClass.getConstructor(
                new Class[] { String.class, HttpServletRequest.class, HttpServletResponse.class });
        return (PageMVCHandler) constructor.newInstance(new Object[] { name, request, response });
    } catch (Exception e) {
        log.error("can't instantiate page [" + name + "]", e);
        throw new InvalidDialogPageHandlerException(name, e);
    }
}

From source file:com.adaptris.core.services.jmx.MetadataValueTranslator.java

private Object convert(String value, String type) throws CoreException {
    try {/*from  w w  w .  jav  a  2  s .co  m*/
        Class<?> clazz = Class.forName(type);
        if (type.equals(String.class.getName()))
            return value;
        if (type.equals(Date.class.getName()))
            return new Date(Long.parseLong(value));
        else
            return clazz.getConstructor(String.class).newInstance(value);
    } catch (Exception e) {
        throw new CoreException(e);
    }
}

From source file:com.utest.webservice.builders.Builder.java

public To toObject(final Class<To> objectClass, final Ti info) throws Exception {
    To result;//  ww  w . j  a  va  2s.  c  o m
    final Constructor<To> constr = objectClass.getConstructor(new Class[] {});
    if (constr == null) {
        throw new IllegalArgumentException("No default constructor found for " + infoClass.getName());
    }
    result = constr.newInstance(new Object[] {});
    PropertyUtils.copyProperties(result, info);
    return result;
}

From source file:com.splunk.hunk.input.packet.DnsPcapRecordReader.java

private PcapReader initPcapReader(String className, DataInputStream is) {
    try {//from  ww  w. jav a 2s  .c  om
        @SuppressWarnings("unchecked")
        Class<? extends PcapReader> pcapReaderClass = (Class<? extends PcapReader>) Class.forName(className);
        Constructor<? extends PcapReader> pcapReaderConstructor = pcapReaderClass
                .getConstructor(DataInputStream.class);
        return pcapReaderConstructor.newInstance(is);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:jfs.sync.JFSFileProducerManager.java

/**
 * Registers all factories and sets the default factory.
 *//*w  ww .j a v a2 s.c  o  m*/
@SuppressWarnings("unchecked")
private JFSFileProducerManager() {
    factories = new HashMap<String, JFSFileProducerFactory>();
    Properties p = new Properties();
    ClassLoader classLoader = this.getClass().getClassLoader();
    try {
        p.load(classLoader.getResourceAsStream("producers.properties"));
    } catch (Exception e) {
        log.error("JFSFileProducerManager()", e);
    } // try/catch
    for (Object property : p.keySet()) {
        String className = "" + property;
        if (className.startsWith("jfs.sync.")) {
            if ("on".equals(p.getProperty(className))) {
                try {
                    Class<JFSFileProducerFactory> c = (Class<JFSFileProducerFactory>) classLoader
                            .loadClass(className);
                    Constructor<JFSFileProducerFactory> constructor = c.getConstructor(new Class<?>[0]);
                    JFSFileProducerFactory factory = constructor.newInstance(new Object[0]);
                    String name = factory.getName();
                    factories.put(name, factory);
                } catch (Exception e) {
                    log.error("JFSFileProducerManager()", e);
                } // try/catch
            } // if
        } // if
    } // for
    defaultFactory = factories.get(JFSLocalFileProducerFactory.SCHEME_NAME);
}

From source file:fitnesse.responders.ResponderFactory.java

private Responder newResponderInstance(Class<?> responderClass) throws InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    try {/*from w ww  .j av a2  s.co  m*/
        Constructor<?> constructor = responderClass.getConstructor(String.class);
        return (Responder) constructor.newInstance(rootPath);
    } catch (NoSuchMethodException e) {
        Constructor<?> constructor = responderClass.getConstructor();
        return (Responder) constructor.newInstance();
    }
}

From source file:com.haulmont.chile.core.datatypes.Datatypes.java

private Datatypes() {
    SAXReader reader = new SAXReader();
    URL resource = Datatypes.class.getResource("/datatypes.xml");
    if (resource == null) {
        log.info("Can't find /datatypes.xml, using default datatypes settings");
        resource = Datatypes.class.getResource("/com/haulmont/chile/core/datatypes/datatypes.xml");
    }/*from  w  w  w .  ja  v a2s.  c  om*/

    try {
        Document document = reader.read(resource);
        Element element = document.getRootElement();

        List<Element> datatypeElements = element.elements("datatype");
        for (Element datatypeElement : datatypeElements) {
            String datatypeClassName = datatypeElement.attributeValue("class");
            try {
                Datatype datatype;
                Class<Datatype> datatypeClass = ReflectionHelper.getClass(datatypeClassName);
                try {
                    final Constructor<Datatype> constructor = datatypeClass.getConstructor(Element.class);
                    datatype = constructor.newInstance(datatypeElement);
                } catch (Throwable e) {
                    datatype = datatypeClass.newInstance();
                }

                __register(datatype);
            } catch (Throwable e) {
                log.error(String.format("Fail to load datatype '%s'", datatypeClassName), e);
            }
        }
    } catch (DocumentException e) {
        log.error("Fail to load datatype settings", e);
    }
}