Example usage for java.lang Class getConstructors

List of usage examples for java.lang Class getConstructors

Introduction

In this page you can find the example usage for java.lang Class getConstructors.

Prototype

@CallerSensitive
public Constructor<?>[] getConstructors() throws SecurityException 

Source Link

Document

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

Usage

From source file:org.jrimum.utilix.text.Field.java

/**
 * L campos texto (String) ou numricos que pode ser obtidos a partir de uma String,
 * usando, por exemplo, o construtor ou o mtodo <code>valueOf</code>.
 * //www  .  ja  v  a  2 s  .c  om
 * @param valueAsString
 */
@SuppressWarnings("unchecked")
private void readStringOrNumericField(String valueAsString) {

    Class<?> c = value.getClass();

    for (Constructor<?> cons : c.getConstructors()) {

        if (cons.getParameterTypes().length == 1) {
            if (cons.getParameterTypes()[0].equals(String.class)) {
                try {

                    value = (G) cons.newInstance(valueAsString);

                } catch (IllegalArgumentException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                } catch (InstantiationException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                } catch (IllegalAccessException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                } catch (InvocationTargetException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                }
            }
        }
    }
}

From source file:org.lansir.beautifulgirls.proxy.ProxyInvocationHandler.java

/** 
 * Dynamic proxy invoke// w  w  w  .j  ava2  s  .c  o m
 */
public Object invoke(Object proxy, Method method, Object[] args)
        throws AkInvokeException, AkServerStatusException, AkException, Exception {
    AkPOST akPost = method.getAnnotation(AkPOST.class);
    AkGET akGet = method.getAnnotation(AkGET.class);

    AkAPI akApi = method.getAnnotation(AkAPI.class);
    Annotation[][] annosArr = method.getParameterAnnotations();
    String invokeUrl = akApi.url();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    // AkApiParams to hashmap, filter out of null-value
    HashMap<String, File> filesToSend = new HashMap<String, File>();
    HashMap<String, String> paramsMapOri = new HashMap<String, String>();
    HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri);
    // Record this invocation
    ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo();
    apiInvokeInfo.apiName = method.getName();
    apiInvokeInfo.paramsMap.putAll(paramsMap);
    apiInvokeInfo.url = invokeUrl;
    // parse '{}'s in url
    invokeUrl = parseUrlbyParams(invokeUrl, paramsMap);
    // cleared hashmap to params, and filter out of the null value
    Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, String> entry = iter.next();
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    // get the signature string if using
    AkSignature akSig = method.getAnnotation(AkSignature.class);
    if (akSig != null) {
        Class<?> clazzSignature = akSig.using();
        if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME
                && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) {
            InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance();
            String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri);
            String sigParamName = is.getSignatureParamName();
            if (sigValue != null && sigParamName != null && sigValue.length() > 0
                    && sigParamName.length() > 0) {
                params.add(new BasicNameValuePair(sigParamName, sigValue));
            }
        }
    }

    // choose POST GET PUT DELETE to use for this invoke
    String retString = "";
    if (akGet != null) {
        StringBuilder sbUrl = new StringBuilder(invokeUrl);
        if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) {
            sbUrl.append("?");
        }
        for (NameValuePair nvp : params) {
            sbUrl.append(nvp.getName());
            sbUrl.append("=");
            sbUrl.append(nvp.getValue());
            sbUrl.append("&");
        } // now default using UTF-8, maybe improved later
        retString = HttpInvoker.get(sbUrl.toString());
    } else if (akPost != null) {
        if (filesToSend.isEmpty()) {
            retString = HttpInvoker.post(invokeUrl, params);
        } else {
            retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend);
        }
    } else { // use POST for default
        retString = HttpInvoker.post(invokeUrl, params);
    }

    // invoked, then add to history
    //ApiStats.addApiInvocation(apiInvokeInfo);

    //Log.d(TAG, retString);

    // parse the return-string
    Class<?> returnType = method.getReturnType();
    try {
        if (String.class.equals(returnType)) { // the result return raw string
            return retString;
        } else { // return object using json decode
            return JsonMapper.json2pojo(retString, returnType);
        }
    } catch (IOException e) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, e.getMessage(), e);
    }
    /*
     * also can use gson like this eg. 
     *  Gson gson = new Gson();
     *  return gson.fromJson(HttpInvoker.post(url, params), returnType);
     */
}

From source file:org.omnaest.utils.reflection.ReflectionUtils.java

/**
 * Resolves a matching constructor for the given type and the given parameter types
 * /*from  ww w .  java  2s  .  com*/
 * @param type
 * @param parameterTypes
 * @return
 */
public static <C> Constructor<C> resolveConstructorFor(Class<C> type, Class<?>... parameterTypes) {
    //
    Constructor<C> retval = null;

    //
    if (type != null) {
        //
        @SuppressWarnings("unchecked")
        Constructor<C>[] constructors = (Constructor<C>[]) type.getConstructors();
        if (constructors != null) {
            for (Constructor<C> constructor : constructors) {
                Class<?>[] parameterTypesOfContstructor = constructor.getParameterTypes();
                boolean areConstructorTypesAssignableFromParameterTypes = areAssignableFrom(
                        parameterTypesOfContstructor, parameterTypes);
                if (areConstructorTypesAssignableFromParameterTypes) {
                    retval = constructor;
                    break;
                }
            }
        }
    }

    //
    return retval;
}

From source file:tiemens.util.instancer.antlr.InstancerCode.java

/**
 * Loop through the constructors, find the best possible. 
 *///from   www.j  av  a2s. c o  m
private Constructor<?> getConstructorBySelecting(Class<?> dclz, Class<?>[] parameterTypes)
        throws NoSuchMethodException {
    Constructor<?> ret = null;
    for (Constructor<?> candidate : dclz.getConstructors()) {
        Class<?>[] types = candidate.getParameterTypes();
        boolean success = false;
        logger.fine(".Checking constructor for " + dclz.getName() + " [types=" + types + "]" + " : "
                + Arrays.toString(types));
        if ((types == null) || (types.length == 0)) {
            logger.fine("--Special case void");
            if ((parameterTypes == null) || (parameterTypes.length == 0)) {
                success = true;
            }
        } else if (parameterTypes == null) {
            success = false;
        } else if (types.length == parameterTypes.length) {
            success = true;

            for (int i = 0, n = types.length; i < n; i++) {
                if (!correctIsAssignableFrom(types[i], parameterTypes[i])) {
                    success = false;
                }
            }
        }
        if (success) {
            logger.fine("..success");
            ret = candidate;
            break;
        } else {
            logger.fine("..failed");
        }
    }
    return ret;
}

From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java

public FunctionImplementationRegistry(DrillConfig config, ScanResult classpathScan) {
    Stopwatch w = Stopwatch.createStarted();

    logger.debug("Generating function registry.");
    localFunctionRegistry = new LocalFunctionRegistry(classpathScan);

    Set<Class<? extends PluggableFunctionRegistry>> registryClasses = classpathScan
            .getImplementations(PluggableFunctionRegistry.class);

    for (Class<? extends PluggableFunctionRegistry> clazz : registryClasses) {
        for (Constructor<?> c : clazz.getConstructors()) {
            Class<?>[] params = c.getParameterTypes();
            if (params.length != 1 || params[0] != DrillConfig.class) {
                logger.warn(/*from  www.  j  av a 2  s  .co m*/
                        "Skipping PluggableFunctionRegistry constructor {} for class {} since it doesn't implement a "
                                + "[constructor(DrillConfig)]",
                        c, clazz);
                continue;
            }

            try {
                PluggableFunctionRegistry registry = (PluggableFunctionRegistry) c.newInstance(config);
                pluggableFuncRegistries.add(registry);
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                logger.warn("Unable to instantiate PluggableFunctionRegistry class '{}'. Skipping it.", clazz,
                        e);
            }

            break;
        }
    }
    logger.info("Function registry loaded.  {} functions loaded in {} ms.", localFunctionRegistry.size(),
            w.elapsed(TimeUnit.MILLISECONDS));
    this.remoteFunctionRegistry = new RemoteFunctionRegistry(new UnregistrationListener());
    this.localUdfDir = getLocalUdfDir(config);
}

From source file:pt.webdetails.cpf.repository.pentaho.unified.UnifiedRepositoryAccess.java

public InputStream getFileInputStream(String path) throws IOException {

    RepositoryFile file = getRepositoryFile(path);

    if (file == null) {
        return null;
    }/*from   w w  w .j  a  va2s . c o  m*/

    try {
        SimpleRepositoryFileData data = getRepository().getDataForRead(file.getId(),
                SimpleRepositoryFileData.class);
        return data.getInputStream();
    } catch (UnifiedRepositoryException ure) {
        // CDA-93: Since 5.1, ktrs are stored as NodeRepositoryFileData instead of SimpleRepositoryFileData on EE
        // We need to check:
        // 1. if we're on EE
        // 2. whether the resource is a ktr or a kjb to load the approriate Converter. Otherwise we'll return the
        // serialization of the node
        NodeRepositoryFileData data = getRepository().getDataForRead(file.getId(),
                NodeRepositoryFileData.class);
        IPluginManager pManager = PentahoSystem.get(IPluginManager.class);
        ClassLoader classLoader = pManager.getClassLoader("pdi-platform-plugin");
        if (classLoader != null) {
            //It's an EE server - get the converter class name given the file type
            String converterClassName = path.endsWith(".ktr")
                    ? "com.pentaho.repository.importexport.StreamToTransNodeConverter"
                    : path.endsWith(".kjb") ? "com.pentaho.repository.importexport.StreamToJobNodeConverter"
                            : null;

            if (converterClassName != null) {
                try {
                    Class converterClass = classLoader.loadClass(converterClassName);
                    Object converterInstance = converterClass.getConstructors()[0].newInstance(getRepository());
                    Method m = converterClass.getMethod("convert", new Class[] { Serializable.class });
                    return (InputStream) m.invoke(converterInstance, file.getId());
                } catch (ClassNotFoundException e) {
                    logger.error("Did not find expected converter class for resource: " + converterClassName
                            + ". Returning default conversion", e);
                } catch (InvocationTargetException e) {
                    logger.error("Error invoking constructor for converter class. Returning default conversion",
                            e);
                } catch (InstantiationException e) {
                    logger.error("Error invoking constructor for converter class. Returning default conversion",
                            e);
                } catch (IllegalAccessException e) {
                    logger.error("Error invoking constructor for converter class. Returning default conversion",
                            e);
                } catch (NoSuchMethodException e) {
                    logger.error("convert method not found in converter class. ", e);
                }
            }
        }

        return new ByteArrayInputStream(data.getNode().toString().getBytes("UTF8"));
    }
}

From source file:org.diorite.impl.bean.BeanScanner.java

private void processClass(final Class<?> clazz) throws BeanException {
    // Bean registration by class
    if (clazz.isAnnotationPresent(DioriteBean.class)) {
        final DioriteBean beanInfo = clazz.getAnnotation(DioriteBean.class);
        final BeanContainer beanContainer = new BeanContainer(clazz, new ClassBeanProvider(clazz));

        this.beanManager.registerBean(beanContainer);
    }// www.j  a  v  a 2s  . co  m

    // Bean registration by constructor
    for (final Constructor<?> constructor : clazz.getConstructors()) {
        if (constructor.isAnnotationPresent(DioriteBean.class)) {
            final DioriteBean beanInfo = constructor.getAnnotation(DioriteBean.class);
            final BeanContainer beanContainer = new BeanContainer(clazz,
                    new ConstructorBeanProvider(constructor));

            this.beanManager.registerBean(beanContainer);
        }
    }

    // Bean registration by method
    for (final Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(DioriteBean.class)) {
            final Class<?> returnType = method.getReturnType();
            if (returnType.equals(Void.TYPE) || returnType.isPrimitive()) {
                throw new BeanRegisteringException(MessageFormat.format(
                        "Can't register method '{0}' in class '{1}' as Diorite Bean. Method must return object.",
                        method.getName(), clazz.getName()));
            } else if (returnType.getPackage().equals(JAVA_PACKAGE)) {
                throw new BeanRegisteringException(MessageFormat.format(
                        "Can't register method '{0}' in class '{1}' as Diorite Bean. Method can't return object from java package.",
                        method.getName(), clazz.getName()));
            }
            final DioriteBean beanInfo = method.getAnnotation(DioriteBean.class);

            final BeanContainer beanContainer = new BeanContainer(returnType, new MethodBeanProvider(method));
            this.beanManager.registerBean(beanContainer);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(InjectedValue.class)) {
            this.beanManager.addInjectorCode(clazz);
            break;
        }
    }
}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.KPMEAccrualCategoryBucket.java

private void initialize(AccrualCategory accrualCategory) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
    List<LeaveBalance> leaveBalances = new ArrayList<LeaveBalance>();
    for (Class<LeaveBalance> leaveBalance : baseBalanceList) {
        Constructor<?>[] constructors = leaveBalance.getConstructors();
        Object[] args = new Object[2];
        args[0] = accrualCategory;//from w ww. ja  v a2 s. c o m
        args[2] = principalCalendar;
        Constructor<?> constructor = constructors[0];
        LeaveBalance myLeaveBalance = (LeaveBalance) constructor.newInstance(args);
        leaveBalances.add(myLeaveBalance);
    }
    this.leaveBalances.put(accrualCategory.getLmAccrualCategoryId(), leaveBalances);
}

From source file:com.opensymphony.xwork2.util.finder.DefaultClassFinder.java

public List<Constructor> findAnnotatedConstructors(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();//  w  ww . ja v  a2s .c o m
    List<ClassInfo> seen = new ArrayList<ClassInfo>();
    List<Constructor> constructors = new ArrayList<Constructor>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && "<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Constructor constructor : clazz.getConstructors()) {
                    if (constructor.isAnnotationPresent(annotation)) {
                        constructors.add(constructor);
                    }
                }
            } catch (Throwable e) {
                LOG.error("Error loading class [{}]", classInfo.getName(), e);
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return constructors;
}

From source file:org.apache.struts2.convention.DefaultClassFinder.java

public List<Constructor> findAnnotatedConstructors(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();//from   w ww. j a  va2 s  . c  o m
    List<ClassInfo> seen = new ArrayList<>();
    List<Constructor> constructors = new ArrayList<>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && "<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Constructor constructor : clazz.getConstructors()) {
                    if (constructor.isAnnotationPresent(annotation)) {
                        constructors.add(constructor);
                    }
                }
            } catch (Throwable e) {
                LOG.error("Error loading class [{}]", classInfo.getName(), e);
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return constructors;
}