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:com.frameworkset.platform.sanylog.common.BeanConvertUtil.java

/**
 * Map??Bean?.//from w ww.  ja  v a2 s  . c o  m
 * 
 * @param clazz
 * @param dataMap ?Map
 * @param fieldMap Map??fieldName
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException 
 */
public static <T> T convert(Class<T> clazz, Map<String, Object> dataMap, Map<String, String> fieldMap)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException {
    T obj = clazz.newInstance();
    ClassInfo classInfo = ClassUtil.getClassInfo(clazz);
    for (String mapKey : fieldMap.keySet()) {
        Object value = dataMap.get(mapKey);
        String fieldName = fieldMap.get(mapKey);
        if (value != null) {
            //classInfo.getDeclaredField(fieldName).set(obj, value);
            PropertieDescription pd = classInfo.getPropertyDescriptor(fieldName);
            //??
            Class<?> pclazz = pd.getPropertyType();

            if (Timestamp.class.isAssignableFrom(pclazz)) {
                if (value instanceof Date) {
                    pd.setValue(obj, new Timestamp(((Date) value).getTime()));
                }
            } else if (Date.class.isAssignableFrom(pclazz)) {
                //String
                if (value instanceof Date) {
                    pd.setValue(obj, value);
                }
            } else {
                Object targetValue = pclazz.getConstructor(String.class).newInstance(value.toString());
                if (String.class.isAssignableFrom(pclazz) && value instanceof Number) {
                    targetValue = new DecimalFormat("0").format(value);
                }
                pd.setValue(obj, targetValue);
            }
            //PropertyUtils.setProperty(obj, fieldName, value);
        }
    }
    return obj;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.WSDUtils.java

/**
 * Read key-value pairs of the specified types from the specified columns of
 * a delimited text file into a Map./* www  . j  av  a  2s.c  om*/
 *
 * @param url
 *            Location of the file to read
 * @param keyColumn
 *            The index of the column giving the keys
 * @param keyClass
 *            The class of the key
 * @param valueColumn
 *            The index of the column giving the values
 * @param valueClass
 *            The class of the value
 * @param delimiterRegex
 *            A regular expression for the field delimiter
 * @return A map of keys to values
 * @throws IOException
 * @throws IllegalArgumentException
 */
public static <K, V> Map<K, V> readMap(final URL url, final int keyColumn, final Class<K> keyClass,
        final int valueColumn, final Class<V> valueClass, final String delimiterRegex)
        throws IOException, IllegalArgumentException {
    Map<K, V> map = new HashMap<K, V>();
    InputStream is = url.openStream();
    String content = IOUtils.toString(is, "UTF-8");
    BufferedReader br = new BufferedReader(new StringReader(content));

    Constructor<K> keyConstructor;
    Constructor<V> valueConstructor;
    try {
        keyConstructor = keyClass.getConstructor(String.class);
        valueConstructor = valueClass.getConstructor(String.class);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }

    String line;
    String[] lineParts;

    while ((line = br.readLine()) != null) {
        lineParts = line.split(delimiterRegex);
        K key;
        V value;
        try {
            key = keyConstructor.newInstance(lineParts[keyColumn - 1]);
            value = valueConstructor.newInstance(lineParts[valueColumn - 1]);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
        map.put(key, value);
    }
    return map;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.WSDUtils.java

/**
 * Read key-value pairs of the specified types from the specified columns of
 * a delimited text file into a Multimap.
 *
 * @param url/*from  w  w w  .  ja v a  2 s  .  com*/
 *            Location of the file to read
 * @param keyColumn
 *            The index of the column giving the keys
 * @param keyClass
 *            The class of the key
 * @param valueColumn
 *            The index of the column giving the values
 * @param valueClass
 *            The class of the value
 * @param delimiterRegex
 *            A regular expression for the field delimiter
 * @return A map of keys to values
 * @throws IOException
 * @throws IllegalArgumentException
 */
public static <K, V> Multimap<K, V> readMultimap(final URL url, final int keyColumn, final Class<K> keyClass,
        final int valueColumn, final Class<V> valueClass, final String delimiterRegex)
        throws IOException, IllegalArgumentException {
    Multimap<K, V> map = HashMultimap.create();
    InputStream is = url.openStream();
    String content = IOUtils.toString(is, "UTF-8");
    BufferedReader br = new BufferedReader(new StringReader(content));

    Constructor<K> keyConstructor;
    Constructor<V> valueConstructor;
    try {
        keyConstructor = keyClass.getConstructor(String.class);
        valueConstructor = valueClass.getConstructor(String.class);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }

    String line;
    String[] lineParts;

    while ((line = br.readLine()) != null) {
        lineParts = line.split(delimiterRegex);
        K key;
        V value;
        try {
            key = keyConstructor.newInstance(lineParts[keyColumn - 1]);
            value = valueConstructor.newInstance(lineParts[valueColumn - 1]);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
        map.put(key, value);
    }
    return map;
}

From source file:eu.stratosphere.nephele.jobmanager.JobManagerUtils.java

/**
 * Tries to locate a class with given name and to
 * instantiate a {@link AbstractScheduler} object from it.
 * //from w w  w  . ja va 2s  .  c om
 * @param schedulerClassName
 *        the name of the class to instantiate the scheduler object from
 * @param deploymentManager
 *        the deployment manager which shall be passed on to the scheduler
 * @param instanceManager
 *        the instance manager which shall be passed on to the scheduler
 * @return the {@link AbstractScheduler} object instantiated from the class with the provided name
 */
@SuppressWarnings("unchecked")
static AbstractScheduler loadScheduler(final String schedulerClassName,
        final DeploymentManager deploymentManager, final InstanceManager instanceManager) {

    Class<? extends AbstractScheduler> schedulerClass;
    try {
        schedulerClass = (Class<? extends AbstractScheduler>) Class.forName(schedulerClassName);
    } catch (ClassNotFoundException e) {
        LOG.error("Cannot find class " + schedulerClassName + ": " + StringUtils.stringifyException(e));
        return null;
    }

    Constructor<? extends AbstractScheduler> constructor;

    try {

        Class<?>[] constructorArgs = { DeploymentManager.class, InstanceManager.class };
        constructor = schedulerClass.getConstructor(constructorArgs);
    } catch (NoSuchMethodException e) {
        LOG.error("Cannot create scheduler: " + StringUtils.stringifyException(e));
        return null;
    } catch (SecurityException e) {
        LOG.error("Cannot create scheduler: " + StringUtils.stringifyException(e));
        return null;
    }

    AbstractScheduler scheduler;

    try {
        scheduler = constructor.newInstance(deploymentManager, instanceManager);
    } catch (InstantiationException e) {
        LOG.error("Cannot create scheduler: " + StringUtils.stringifyException(e));
        return null;
    } catch (IllegalAccessException e) {
        LOG.error("Cannot create scheduler: " + StringUtils.stringifyException(e));
        return null;
    } catch (IllegalArgumentException e) {
        LOG.error("Cannot create scheduler: " + StringUtils.stringifyException(e));
        return null;
    } catch (InvocationTargetException e) {
        LOG.error("Cannot create scheduler: " + StringUtils.stringifyException(e));
        return null;
    }

    return scheduler;
}

From source file:BrowserLauncher.java

/**
 * Called by a static initializer to load any classes, fields, and methods required at runtime
 * to locate the user's web browser./*from  www.j ava 2 s  .c o  m*/
 * @return <code>true</code> if all intialization succeeded
 *         <code>false</code> if any portion of the initialization failed
 */
private static boolean loadClasses() {
    switch (jvm) {
    case MRJ_2_0:
        try {
            Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
            Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
            Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
            Class aeClass = Class.forName("com.apple.MacOS.ae");
            aeDescClass = Class.forName("com.apple.MacOS.AEDesc");

            aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] { int.class });
            appleEventConstructor = appleEventClass.getDeclaredConstructor(
                    new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
            aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });

            makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[] { String.class });
            putParameter = appleEventClass.getDeclaredMethod("putParameter",
                    new Class[] { int.class, aeDescClass });
            sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] {});

            Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
            keyDirectObject = (Integer) keyDirectObjectField.get(null);
            Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
            kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
            Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
            kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;
    case MRJ_2_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
            Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
            kSystemFolderType = systemFolderField.get(null);
            findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
            getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
            getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchFieldException nsfe) {
            errorMessage = nsfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (SecurityException se) {
            errorMessage = se.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;
    case MRJ_3_0:
        try {
            Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
            Constructor constructor = linker.getConstructor(new Class[] { Class.class });
            linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        } catch (InvocationTargetException ite) {
            errorMessage = ite.getMessage();
            return false;
        } catch (InstantiationException ie) {
            errorMessage = ie.getMessage();
            return false;
        } catch (IllegalAccessException iae) {
            errorMessage = iae.getMessage();
            return false;
        }
        break;
    case MRJ_3_1:
        try {
            mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
            openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
        } catch (ClassNotFoundException cnfe) {
            errorMessage = cnfe.getMessage();
            return false;
        } catch (NoSuchMethodException nsme) {
            errorMessage = nsme.getMessage();
            return false;
        }
        break;
    default:
        break;
    }
    return true;
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Get the reconnection policy.//w  w w.  j a  v  a2 s .c  o m
 */
public static ReconnectionPolicy getReconnectionPolicy(String rcString, String parameters)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    ReconnectionPolicy policy = null;
    //ReconnectionPolicy childPolicy = null;
    if (!rcString.contains(".")) {
        rcString = "com.datastax.driver.core.policies." + rcString;
    }

    if (parameters.length() > 0) {
        // Child policy or parameters have been specified
        String paramsRegex = "([^,]+\\(.+?\\))|([^,]+)";
        Pattern param_pattern = Pattern.compile(paramsRegex);
        Matcher lb_matcher = param_pattern.matcher(parameters);

        ArrayList<Object> paramList = Lists.newArrayList();
        ArrayList<Class> primaryParametersClasses = Lists.newArrayList();
        int nb = 0;
        while (lb_matcher.find()) {
            if (lb_matcher.groupCount() > 0) {
                try {
                    if (lb_matcher.group().contains("(") && !lb_matcher.group().trim().startsWith("(")) {
                        // We are dealing with child policies here
                        primaryParametersClasses.add(LoadBalancingPolicy.class);
                        // Parse and add child policy to the parameter list
                        paramList.add(parseReconnectionPolicy(lb_matcher.group()));
                        nb++;
                    } else {
                        // We are dealing with parameters that are not policies here
                        String param = lb_matcher.group();
                        if (param.contains("'") || param.contains("\"")) {
                            primaryParametersClasses.add(String.class);
                            paramList.add(new String(param.trim().replace("'", "").replace("\"", "")));
                        } else if (param.contains(".") || param.toLowerCase().contains("(double)")
                                || param.toLowerCase().contains("(float)")) {
                            // gotta allow using float or double
                            if (param.toLowerCase().contains("(double)")) {
                                primaryParametersClasses.add(double.class);
                                paramList.add(Double.parseDouble(param.replace("(double)", "").trim()));
                            } else {
                                primaryParametersClasses.add(float.class);
                                paramList.add(Float.parseFloat(param.replace("(float)", "").trim()));
                            }
                        } else {
                            if (param.toLowerCase().contains("(long)")) {
                                primaryParametersClasses.add(long.class);
                                paramList.add(Long.parseLong(param.toLowerCase().replace("(long)", "").trim()));
                            } else {
                                primaryParametersClasses.add(int.class);
                                paramList
                                        .add(Integer.parseInt(param.toLowerCase().replace("(int)", "").trim()));
                            }
                        }
                        nb++;
                    }
                } catch (Exception e) {
                    log.error("Could not parse the Cassandra reconnection policy! " + e.getMessage());
                }
            }
        }

        if (nb > 0) {
            // Instantiate load balancing policy with parameters
            Class<?> clazz = Class.forName(rcString);
            Constructor<?> constructor = clazz.getConstructor(
                    primaryParametersClasses.toArray(new Class[primaryParametersClasses.size()]));

            return (ReconnectionPolicy) constructor
                    .newInstance(paramList.toArray(new Object[paramList.size()]));
        }
        // Only one policy has been specified, with no parameter or child policy
        Class<?> clazz = Class.forName(rcString);
        policy = (ReconnectionPolicy) clazz.newInstance();
        return policy;
    }
    Class<?> clazz = Class.forName(rcString);
    policy = (ReconnectionPolicy) clazz.newInstance();
    return policy;
}

From source file:net.itransformers.idiscover.core.DiscoveryManager.java

private static DiscoveryHelperFactory createDiscoveryHelperFactory(DiscoveryManagerType discoveryManagerType)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        InvocationTargetException {
    net.itransformers.idiscover.core.discoveryconfig.DiscoveryHelperType discoveryHelperType = discoveryManagerType
            .getDiscoveryHelper();//  w ww. java2s. com
    String clazzStr = discoveryHelperType.getClazz();
    Class<?> clazz = Class.forName(clazzStr);
    Map<String, String> discoveryHelerpParams = new HashMap<String, String>();

    for (ParamType s : discoveryHelperType.getParameters().getParam()) {
        discoveryHelerpParams.put(s.getName(), s.getValue());
    }
    Constructor constructor = clazz.getConstructor(Map.class);
    return (DiscoveryHelperFactory) constructor.newInstance(discoveryHelerpParams);
}

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

public static <C> C createInstanceFromClassNameWithArguments(ClassLoader classLoader, String classWithArguments,
        Class<C> expectedType) throws UndeclaredThrowableException {
    try {//from   w  w  w. j a va 2 s  .  co m
        List<String> parameters = toList(escapeValues(classWithArguments.split(";")));
        Class<?> klass = ClassUtils.loadClass(classLoader, shift(parameters));

        if (!expectedType.isAssignableFrom(klass)) {
            throw new IllegalArgumentException(
                    "Class " + expectedType.getName() + " is not assignable from " + klass.getName());
        }

        if (parameters.size() == 0) {
            return expectedType.cast(klass.newInstance());
        }

        String[] args = parameters.toArray(new String[parameters.size()]);
        Constructor<?> constructor = klass.getConstructor(args.getClass());
        return expectedType.cast(constructor.newInstance(new Object[] { args }));
    } catch (ClassNotFoundException e) {
        throw new UndeclaredThrowableException(e);
    } catch (InstantiationException e) {
        throw new UndeclaredThrowableException(e);
    } catch (IllegalAccessException e) {
        throw new UndeclaredThrowableException(e);
    } catch (NoSuchMethodException e) {
        throw new UndeclaredThrowableException(e);
    } catch (InvocationTargetException e) {
        throw new UndeclaredThrowableException(e);
    }
}

From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java

/**
 * /*w ww. j av a2  s.  c o  m*/
 */
public static JRSaxParserFactory getFactory(JasperReportsContext jasperReportsContext, String className) {
    JRSaxParserFactory factory = null;
    try {
        @SuppressWarnings("unchecked")
        Class<? extends JRSaxParserFactory> clazz = (Class<? extends JRSaxParserFactory>) JRClassLoader
                .loadClassForName(className);
        if (!JRSaxParserFactory.class.isAssignableFrom(clazz)) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_INCOMPATIBLE_CLASS,
                    new Object[] { className, JRSaxParserFactory.class.getName() });
        }

        try {
            Constructor<? extends JRSaxParserFactory> constr = clazz
                    .getConstructor(new Class[] { JasperReportsContext.class });
            factory = constr.newInstance(jasperReportsContext);
        } catch (NoSuchMethodException | InvocationTargetException e) {
            //ignore
        }

        if (factory == null) {
            factory = clazz.getDeclaredConstructor().newInstance();
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
            | InvocationTargetException e) {
        throw new JRRuntimeException(e);
    }

    return factory;
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Get the load balancing policy.//from  w  ww.  ja v  a  2 s . co m
 */
public static LoadBalancingPolicy getLbPolicy(String lbString, String parameters)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    LoadBalancingPolicy policy = null;
    if (!lbString.contains(".")) {
        lbString = "com.datastax.driver.core.policies." + lbString;
    }

    if (parameters.length() > 0) {
        // Child policy or parameters have been specified
        String paramsRegex = "([^,]+\\(.+?\\))|([^,]+)";
        Pattern param_pattern = Pattern.compile(paramsRegex);
        Matcher lb_matcher = param_pattern.matcher(parameters);

        ArrayList<Object> paramList = Lists.newArrayList();
        ArrayList<Class> primaryParametersClasses = Lists.newArrayList();
        int nb = 0;
        while (lb_matcher.find()) {
            if (lb_matcher.groupCount() > 0) {
                try {
                    if (lb_matcher.group().contains("(") && !lb_matcher.group().trim().startsWith("(")) {
                        // We are dealing with child policies here
                        primaryParametersClasses.add(LoadBalancingPolicy.class);
                        // Parse and add child policy to the parameter list
                        paramList.add(parseLbPolicy(lb_matcher.group()));
                        nb++;
                    } else {
                        // We are dealing with parameters that are not policies here
                        String param = lb_matcher.group();
                        if (param.contains("'") || param.contains("\"")) {
                            primaryParametersClasses.add(String.class);
                            paramList.add(new String(param.trim().replace("'", "").replace("\"", "")));
                        } else if (param.contains(".") || param.toLowerCase().contains("(double)")
                                || param.toLowerCase().contains("(float)")) {
                            // gotta allow using float or double
                            if (param.toLowerCase().contains("(double)")) {
                                primaryParametersClasses.add(double.class);
                                paramList.add(Double.parseDouble(param.replace("(double)", "").trim()));
                            } else {
                                primaryParametersClasses.add(float.class);
                                paramList.add(Float.parseFloat(param.replace("(float)", "").trim()));
                            }
                        } else {
                            if (param.toLowerCase().contains("(long)")) {
                                primaryParametersClasses.add(long.class);
                                paramList.add(Long.parseLong(param.toLowerCase().replace("(long)", "").trim()));
                            } else {
                                primaryParametersClasses.add(int.class);
                                paramList
                                        .add(Integer.parseInt(param.toLowerCase().replace("(int)", "").trim()));
                            }
                        }
                        nb++;
                    }
                } catch (Exception e) {
                    log.error("Could not parse the Cassandra load balancing policy! " + e.getMessage());
                }
            }
        }
        if (nb > 0) {
            // Instantiate load balancing policy with parameters
            if (lbString.toLowerCase().contains("latencyawarepolicy")) {
                //special sauce for the latency aware policy which uses a builder subclass to instantiate
                Builder builder = LatencyAwarePolicy.builder((LoadBalancingPolicy) paramList.get(0));

                builder.withExclusionThreshold((Double) paramList.get(1));
                builder.withScale((Long) paramList.get(2), TimeUnit.MILLISECONDS);
                builder.withRetryPeriod((Long) paramList.get(3), TimeUnit.MILLISECONDS);
                builder.withUpdateRate((Long) paramList.get(4), TimeUnit.MILLISECONDS);
                builder.withMininumMeasurements((Integer) paramList.get(5));

                return builder.build();

            } else {
                Class<?> clazz = Class.forName(lbString);
                Constructor<?> constructor = clazz.getConstructor(
                        primaryParametersClasses.toArray(new Class[primaryParametersClasses.size()]));

                return (LoadBalancingPolicy) constructor
                        .newInstance(paramList.toArray(new Object[paramList.size()]));
            }
        } else {
            // Only one policy has been specified, with no parameter or child policy
            Class<?> clazz = Class.forName(lbString);
            policy = (LoadBalancingPolicy) clazz.newInstance();
            return policy;
        }
    } else {
        // Only one policy has been specified, with no parameter or child policy
        Class<?> clazz = Class.forName(lbString);
        policy = (LoadBalancingPolicy) clazz.newInstance();
        return policy;
    }
}