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:org.ldp4j.server.IntegrationTestHelper.java

public <T extends HttpUriRequest> T newRequest(String path, Class<? extends T> clazz) {
    try {//  ww  w  .  j av  a  2s.  c o  m
        return clazz.getConstructor(URI.class).newInstance(resourceLocation(path));
    } catch (Exception e) {
        throw new IllegalStateException("Could not create request", e);
    }
}

From source file:org.opendaylight.ovsdb.lib.schema.TableSchema.java

public <E extends TableSchema<E>> E as(Class<E> clazz) {
    try {//  w  w w.j  ava 2s. c o  m
        Constructor<E> instance = clazz.getConstructor(TableSchema.class);
        return instance.newInstance(this);
    } catch (Exception e) {
        throw new RuntimeException("exception constructing instance of clazz " + clazz, e);
    }
}

From source file:de.openknowledge.jaxrs.versioning.conversion.FieldVersionProperty.java

private Object convert(Object value) {
    if (value == null || !isSimple() || type.isAssignableFrom(value.getClass())) {
        return value;
    }/*from  w ww .jav  a 2  s .  c  om*/
    Class<?> targetType = type.isPrimitive() ? ClassUtils.primitiveToWrapper(type) : type;
    try {
        return targetType.getConstructor(String.class).newInstance(value.toString());
    } catch (ReflectiveOperationException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.bstek.dorado.web.servlet.ServletContextResourceLoader.java

public ServletContextResourceLoader(ServletContext servletContext) {
    this.servletContext = servletContext;
    String resourceLoaderClass = servletContext.getInitParameter("resourceLoaderClass");
    if (StringUtils.isNotEmpty(StringUtils.trim(resourceLoaderClass))) {
        ConsoleUtils.outputLoadingInfo("[resourceLoaderClass=" + resourceLoaderClass + "]");

        try {//from  w  w w  .j a  v  a2  s .c  o  m
            @SuppressWarnings("unchecked")
            Class<ResourceLoader> type = ClassUtils.forName(resourceLoaderClass);
            Constructor<ResourceLoader> constr = type.getConstructor(new Class[] { ClassLoader.class });
            resourceLoader = constr.newInstance(new Object[] { getClass().getClassLoader() });
        } catch (Exception e) {
            logger.error(e, e);
        }
    }
}

From source file:com.wabacus.system.dataset.update.JavaUpdateActionProvider.java

public List<AbsUpdateAction> parseAllUpdateActions(String reportTypeKey) {
    if (Tools.isEmpty(strclasses))
        return null;
    ReportBean rbean = this.ownerUpdateBean.getOwner().getReportBean();
    List<String> lstActionscripts = Tools.parseStringToList(this.strclasses, ";", new String[] { "\"", "\"" },
            false);/*from  w  ww .  j a  v a 2 s .c o m*/
    List<AbsUpdateAction> lstResults = new ArrayList<AbsUpdateAction>();
    for (String scriptTmp : lstActionscripts) {
        if (scriptTmp == null || scriptTmp.trim().equals(""))
            continue;
        scriptTmp = scriptTmp.trim();
        String javaname = scriptTmp;
        String params = null;
        int idx1 = scriptTmp.indexOf("(");
        int idx2 = scriptTmp.indexOf(")");
        if (idx1 > 0 && idx2 == scriptTmp.length() - 1) {
            javaname = scriptTmp.substring(0, idx1).trim();
            params = scriptTmp.substring(idx1 + 1, idx2).trim();
        } else if (idx1 >= 0 || idx2 >= 0) {
            throw new WabacusConfigLoadingException("" + rbean.getPath()
                    + "??JAVA" + scriptTmp + "??");
        }
        Object javaActionBean;
        try {
            Class c = ConfigLoadManager.currentDynClassLoader.loadClassByCurrentLoader(javaname);
            javaActionBean = c.getConstructor(new Class[] { AbsEditableReportEditDataBean.class })
                    .newInstance(this.ownerUpdateBean);
        } catch (Exception e) {
            throw new WabacusConfigLoadingException("" + rbean.getPath()
                    + "??JAVA" + scriptTmp + "", e);
        }
        if (!(javaActionBean instanceof AbsUpdateAction)) {
            throw new WabacusConfigLoadingException(
                    "" + rbean.getPath() + "??JAVA" + scriptTmp
                            + "" + AbsUpdateAction.class.getName());
        }
        parseParams(params, reportTypeKey, (AbsUpdateAction) javaActionBean);
        lstResults.add((AbsUpdateAction) javaActionBean);
    }
    return lstResults;
}

From source file:de.openknowledge.cdi.common.property.PropertiesLoader.java

private <T> T newInstance(InjectionPoint injectionPoint, String value, Class<T> type) {
    if (value == null) {
        return null;
    }//from w ww  .jav a  2  s  .  c  om
    try {
        return type.getConstructor(String.class).newInstance(value);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(type.getName() + " must have String-constructor to be injected");
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("String-constructor must be public");
    } catch (InstantiationException e) {
        throw buildIllegalArgumentException(injectionPoint, value, type, e);
    } catch (InvocationTargetException e) {
        throw buildIllegalArgumentException(injectionPoint, value, type, e.getTargetException());
    }
}

From source file:com.mayabot.thriftpool.utils.ReflectUtils.java

/**
 * ???/*  w  ww.  ja v a2s . c o  m*/
 * 
 * @param clazz 
 * @param methodName ??method1(int, String)?????????method2
 * @return 
 * @throws NoSuchMethodException
 * @throws ClassNotFoundException  
 * @throws IllegalStateException ???????
 */
//   public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes)
//           throws NoSuchMethodException, ClassNotFoundException {
//       String signature = clazz.getName() + "." + methodName;
//        if(parameterTypes != null && parameterTypes.length > 0){
//            signature += StringUtils.join(parameterTypes);
//        }
//        Method method = Signature_METHODS_CACHE.get(signature);
//        if(method != null){
//            return method;
//        }
//       if (parameterTypes == null) {
//            List<Method> finded = new ArrayList<Method>();
//            for (Method m : clazz.getMethods()) {
//                if (m.getName().equals(methodName)) {
//                    finded.add(m);
//                }
//            }
//            if (finded.isEmpty()) {
//                throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz);
//            }
//            if(finded.size() > 1) {
//                String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.",
//                        methodName, clazz.getName(), finded.size());
//                throw new IllegalStateException(msg);
//            }
//            method = finded.get(0);
//        } else {
//            Class<?>[] types = new Class<?>[parameterTypes.length];
//            for (int i = 0; i < parameterTypes.length; i ++) {
//                types[i] = ReflectUtils.name2class(parameterTypes[i]);
//            }
//            method = clazz.getMethod(methodName, types);
//            
//        }
//       Signature_METHODS_CACHE.put(signature, method);
//        return method;
//   }

//    public static Method findMethodByMethodName(Class<?> clazz, String methodName)
//          throws NoSuchMethodException, ClassNotFoundException {
//       return findMethodByMethodSignature(clazz, methodName, null);
//    }

public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException {
    Constructor<?> targetConstructor;
    try {
        targetConstructor = clazz.getConstructor(new Class<?>[] { paramType });
    } catch (NoSuchMethodException e) {
        targetConstructor = null;
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 1
                    && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) {
                targetConstructor = constructor;
                break;
            }
        }
        if (targetConstructor == null) {
            throw e;
        }
    }
    return targetConstructor;
}

From source file:com.zotoh.maedr.impl.UserDeviceFactory.java

/**
 * @param type/*from ww w.j  a  v a 2s .  co m*/
 * @param deviceClass
 * @throws Exception
 */
public void add(String type, String deviceClass) throws Exception {

    if (isEmpty(type) || isEmpty(deviceClass)) {
        return;
    }

    if (_devs.containsKey(type)) {
        errBadArg("Device type: " + type + " is already defined.");
    }

    Class<?> z = loadClass(deviceClass);
    Constructor<?> ctor;

    tstArgIsType("device", z, Device.class);
    try {
        ctor = z.getConstructor(DeviceManager.class);
    } catch (Throwable t) {
        throw new InstantiationException("Class: " + deviceClass + " is missing ctor(DeviceManager)");
    }

    _devs.put(type, ctor);
}

From source file:com.baidu.terminator.manager.service.LinkControlServiceImpl.java

private <T> T getPluginInstance(Link link, Class<T> clazz) {
    try {// ww w  . j ava2 s  .c  om
        Constructor<T> constructor = clazz.getConstructor(Link.class);
        T plugin = constructor.newInstance(link);
        return plugin;
    } catch (SecurityException e) {
        throw new SignerInitializationException("InitializationFail", e.getCause());
    } catch (IllegalArgumentException e) {
        throw new SignerInitializationException("InitializationFail", e.getCause());
    } catch (NoSuchMethodException e) {
        throw new SignerInitializationException("InitializationFail", e.getCause());
    } catch (InstantiationException e) {
        throw new SignerInitializationException("InitializationFail", e.getCause());
    } catch (IllegalAccessException e) {
        throw new SignerInitializationException("InitializationFail", e.getCause());
    } catch (InvocationTargetException e) {
        throw new SignerInitializationException("InitializationFail", e.getCause());
    }
}

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  ww  .ja  v a  2  s.  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);
    }
}