Example usage for java.lang.reflect Constructor getParameterTypes

List of usage examples for java.lang.reflect Constructor getParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Constructor getParameterTypes.

Prototype

@Override
public Class<?>[] getParameterTypes() 

Source Link

Usage

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean checkConstructor(Constructor c, Class clss, List<Class> classes) {
    if (!Modifier.isPublic(c.getModifiers())) {
        if (c.getParameterTypes().length != 0 || !Modifier.isProtected(c.getModifiers())) {
            return true;
        }/*from  w  w  w  . jav  a2s  . c  o m*/
    }
    Constructor ca[] = clss.getDeclaredConstructors();
    for (int i = 0; i < ca.length; i++) {
        Constructor constructor = ca[i];
        if (constructor.equals(c)) {
            break;
        }
        if (constructor.getParameterTypes().length == c.getParameterTypes().length) {
            if (c.getParameterTypes().length >= 1
                    && String.class.isAssignableFrom(c.getParameterTypes()[0]) != String.class
                            .isAssignableFrom(constructor.getParameterTypes()[0])) {
                continue;
            }
            return true;
        }
    }
    if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) {
        return true;
    }
    if (!checkParameters(c.getParameterTypes(), classes)) {
        return true;
    }
    return false;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

public static boolean hasNoArgConstructor(Constructor[] constructors) {
    for (Constructor c : constructors) {
        if ((Modifier.isProtected(c.getModifiers()) || Modifier.isPublic(c.getModifiers()))
                && c.getParameterTypes().length == 0) {
            return true;
        }/*  w  ww.j  a  v  a 2s.  com*/
    }
    return false;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Instantiate the given proxy class./*w  w  w  .j  a  v  a2 s  . co m*/
 */
private Proxy instantiateProxy(Class cls, Constructor cons, Object[] args) {
    try {
        if (cons != null)
            return (Proxy) cls.getConstructor(cons.getParameterTypes()).newInstance(args);
        return (Proxy) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(cls));
    } catch (InstantiationException ie) {
        throw new UnsupportedException(_loc.get("cant-newinstance", cls.getSuperclass().getName()));
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof InstantiationException)
            throw new UnsupportedException(_loc.get("cant-newinstance", cls.getSuperclass().getName()));
        else
            throw new GeneralException(cls.getName()).setCause(e);
    } catch (Throwable t) {
        throw new GeneralException(cls.getName()).setCause(t);
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {/*from  w  w w  .  ja  va 2  s.  co  m*/

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Implement the methods in the {@link ProxyCalendar} interface.
 *//*from  w  ww .ja v  a 2  s  .  co m*/
private void addProxyCalendarMethods(BCClass bc, Class type) {
    // calendar copy
    Constructor cons = findCopyConstructor(type);
    Class[] params = (cons == null) ? new Class[0] : cons.getParameterTypes();

    BCMethod m = bc.declareMethod("copy", Object.class, new Class[] { Object.class });
    m.makePublic();
    Code code = m.getCode(true);

    code.anew().setType(type);
    code.dup();
    if (params.length == 1) {
        code.aload().setParam(0);
        code.checkcast().setType(params[0]);
    }
    code.invokespecial().setMethod(type, "<init>", void.class, params);
    if (params.length == 0) {
        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Calendar.class);
        code.invokevirtual().setMethod(Calendar.class, "getTimeInMillis", long.class, null);
        code.invokevirtual().setMethod(type, "setTimeInMillis", void.class, new Class[] { long.class });

        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Calendar.class);
        code.invokevirtual().setMethod(Calendar.class, "isLenient", boolean.class, null);
        code.invokevirtual().setMethod(type, "setLenient", void.class, new Class[] { boolean.class });

        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Calendar.class);
        code.invokevirtual().setMethod(Calendar.class, "getFirstDayOfWeek", int.class, null);
        code.invokevirtual().setMethod(type, "setFirstDayOfWeek", void.class, new Class[] { int.class });

        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Calendar.class);
        code.invokevirtual().setMethod(Calendar.class, "getMinimalDaysInFirstWeek", int.class, null);
        code.invokevirtual().setMethod(type, "setMinimalDaysInFirstWeek", void.class,
                new Class[] { int.class });

        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Calendar.class);
        code.invokevirtual().setMethod(Calendar.class, "getTimeZone", TimeZone.class, null);
        code.invokevirtual().setMethod(type, "setTimeZone", void.class, new Class[] { TimeZone.class });
    }
    code.areturn();
    code.calculateMaxStack();
    code.calculateMaxLocals();

    // new instance factory
    m = bc.declareMethod("newInstance", ProxyCalendar.class, null);
    m.makePublic();
    code = m.getCode(true);
    code.anew().setType(bc);
    code.dup();
    code.invokespecial().setMethod("<init>", void.class, null);
    code.areturn();
    code.calculateMaxStack();
    code.calculateMaxLocals();

    // proxy the protected computeFields method b/c it is called on
    // mutate, and some setters are final and therefore not proxyable
    m = bc.declareMethod("computeFields", void.class, null);
    m.makeProtected();
    code = m.getCode(true);
    code.aload().setThis();
    code.constant().setValue(true);
    code.invokestatic().setMethod(Proxies.class, "dirty", void.class,
            new Class[] { Proxy.class, boolean.class });
    code.aload().setThis();
    code.invokespecial().setMethod(type, "computeFields", void.class, null);
    code.vreturn();
    code.calculateMaxStack();
    code.calculateMaxLocals();
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Implement the methods in the {@link ProxyDate} interface.
 */// w ww  .ja va 2  s.com
private void addProxyDateMethods(BCClass bc, Class type) {
    boolean hasDefaultCons = bc.getDeclaredMethod("<init>", (Class[]) null) != null;
    boolean hasMillisCons = bc.getDeclaredMethod("<init>", new Class[] { long.class }) != null;
    if (!hasDefaultCons && !hasMillisCons)
        throw new UnsupportedException(_loc.get("no-date-cons", type));

    // add a default constructor that delegates to the millis constructor
    BCMethod m;
    Code code;
    if (!hasDefaultCons) {
        m = bc.declareMethod("<init>", void.class, null);
        m.makePublic();
        code = m.getCode(true);
        code.aload().setThis();
        code.invokestatic().setMethod(System.class, "currentTimeMillis", long.class, null);
        code.invokespecial().setMethod(type, "<init>", void.class, new Class[] { long.class });
        code.vreturn();
        code.calculateMaxStack();
        code.calculateMaxLocals();
    }

    // date copy
    Constructor cons = findCopyConstructor(type);
    Class[] params;
    if (cons != null)
        params = cons.getParameterTypes();
    else if (hasMillisCons)
        params = new Class[] { long.class };
    else
        params = new Class[0];

    m = bc.declareMethod("copy", Object.class, new Class[] { Object.class });
    m.makePublic();
    code = m.getCode(true);

    code.anew().setType(type);
    code.dup();
    if (params.length == 1) {
        if (params[0] == long.class) {
            code.aload().setParam(0);
            code.checkcast().setType(Date.class);
            code.invokevirtual().setMethod(Date.class, "getTime", long.class, null);
        } else {
            code.aload().setParam(0);
            code.checkcast().setType(params[0]);
        }
    }
    code.invokespecial().setMethod(type, "<init>", void.class, params);
    if (params.length == 0) {
        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Date.class);
        code.invokevirtual().setMethod(Date.class, "getTime", long.class, null);
        code.invokevirtual().setMethod(type, "setTime", void.class, new Class[] { long.class });
    }
    if ((params.length == 0 || params[0] == long.class) && Timestamp.class.isAssignableFrom(type)) {
        code.dup();
        code.aload().setParam(0);
        code.checkcast().setType(Timestamp.class);
        code.invokevirtual().setMethod(Timestamp.class, "getNanos", int.class, null);
        code.invokevirtual().setMethod(type, "setNanos", void.class, new Class[] { int.class });
    }
    code.areturn();
    code.calculateMaxStack();
    code.calculateMaxLocals();

    // new instance factory
    m = bc.declareMethod("newInstance", ProxyDate.class, null);
    m.makePublic();
    code = m.getCode(true);
    code.anew().setType(bc);
    code.dup();
    code.invokespecial().setMethod("<init>", void.class, null);
    code.areturn();
    code.calculateMaxStack();
    code.calculateMaxLocals();
}

From source file:org.apache.bval.jsr.ClassValidator.java

public <T> Set<ConstraintViolation<T>> validateConstructorReturnValue(
        final Constructor<? extends T> constructor, final T createdObject, final Class<?>... gps) {
    {//from  w  w  w  . ja v  a  2 s  . com
        notNull("Constructor", constructor);
        notNull("Returned value", createdObject);
    }

    final Class<? extends T> declaringClass = constructor.getDeclaringClass();
    final ConstructorDescriptorImpl methodDescriptor = ConstructorDescriptorImpl.class
            .cast(getConstraintsForClass(declaringClass)
                    .getConstraintsForConstructor(constructor.getParameterTypes()));
    if (methodDescriptor == null) {
        throw new ValidationException(
                "Constructor " + constructor + " doesn't belong to class " + declaringClass);
    }

    return validaReturnedValue(
            new NodeImpl.ConstructorNodeImpl(declaringClass.getSimpleName(),
                    Arrays.asList(constructor.getParameterTypes())),
            createdObject, declaringClass, methodDescriptor, gps, null);
}

From source file:org.apache.bval.jsr.ClassValidator.java

public <T> Set<ConstraintViolation<T>> validateConstructorParameters(Constructor<? extends T> constructor,
        Object[] parameterValues, Class<?>... gps) {
    notNull("Constructor", constructor);
    notNull("Groups", gps);
    notNull("Parameters", parameterValues);

    final Class<?> declaringClass = constructor.getDeclaringClass();
    final ConstructorDescriptorImpl constructorDescriptor = ConstructorDescriptorImpl.class
            .cast(getConstraintsForClass(declaringClass)
                    .getConstraintsForConstructor(constructor.getParameterTypes()));
    if (constructorDescriptor == null) { // no constraint
        return Collections.emptySet();
    }/*from   w w w. ja va 2  s.  c o m*/

    // sanity checks
    if (!constructorDescriptor.isValidated(constructor)) {
        if (parameterValues.length == 0) {
            checkValidationAppliesTo(Collections.singleton(constructorDescriptor.getCrossParameterDescriptor()),
                    ConstraintTarget.PARAMETERS);
            checkValidationAppliesTo(constructorDescriptor.getParameterDescriptors(),
                    ConstraintTarget.PARAMETERS);
        } else {
            checkValidationAppliesTo(Collections.singleton(constructorDescriptor.getCrossParameterDescriptor()),
                    ConstraintTarget.IMPLICIT);
            checkValidationAppliesTo(constructorDescriptor.getParameterDescriptors(),
                    ConstraintTarget.IMPLICIT);
        }
        constructorDescriptor.setValidated(constructor);
    }

    // validations
    return validateInvocationParameters(constructor, parameterValues, constructorDescriptor, gps,
            new NodeImpl.ConstructorNodeImpl(declaringClass.getSimpleName(),
                    Arrays.asList(constructor.getParameterTypes())),
            null);
}

From source file:adalid.commons.velocity.Writer.java

private Class<?> getConstructorParameterType(Class<?> wrapper, Class<?> wrappable) {
    Class<?> parameterType = null;
    Constructor<?>[] constructors = wrapper.getConstructors();
    for (Constructor<?> constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(wrappable)) {
            if (parameterType == null || parameterType.isAssignableFrom(parameterTypes[0])) {
                parameterType = parameterTypes[0];
            }//from   w  w w. j  a  va 2  s. co  m
        }
    }
    return parameterType;
}