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:dk.netarkivet.archive.webinterface.BatchGUI.java

/**
 * Method for executing a batchjob.//from   w w w  .java2s.  c  o  m
 *
 * @param context The page context containing the needed information for executing the batchjob.
 */
@SuppressWarnings("rawtypes")
public static void execute(PageContext context) {
    try {
        ServletRequest request = context.getRequest();

        // get parameters
        String filetype = request.getParameter(Constants.FILETYPE_PARAMETER);
        String jobId = request.getParameter(Constants.JOB_ID_PARAMETER);
        String jobName = request.getParameter(Constants.BATCHJOB_PARAMETER);
        String repName = request.getParameter(Constants.REPLICA_PARAMETER);

        FileBatchJob batchjob;

        // Retrieve the list of arguments.
        List<String> args = new ArrayList<String>();
        String arg;
        Integer i = 1;
        // retrieve the constructor to find out how many arguments
        Class c = getBatchClass(jobName);
        Constructor con = findStringConstructor(c);

        // retrieve the arguments and put them into the list.
        while (i <= con.getParameterTypes().length) {
            arg = request.getParameter("arg" + i.toString());
            if (arg != null) {
                args.add(arg);
            } else {
                log.warn("Should contain argument number " + i + ", but "
                        + "found a null instead, indicating missing " + "argument. Use empty string instead.");
                args.add("");
            }
            i++;
        }

        File jarfile = getJarFile(jobName);
        if (jarfile == null) {
            // get the constructor and instantiate it.
            Constructor construct = findStringConstructor(getBatchClass(jobName));
            batchjob = (FileBatchJob) construct.newInstance(args.toArray());
        } else {
            batchjob = new LoadableJarBatchJob(jobName, args, jarfile);
        }

        // get the regular expression.
        String regex = jobId + "-";
        if (filetype.equals(BatchFileType.Metadata.toString())) {
            regex += Constants.REGEX_METADATA;
        } else if (filetype.equals(BatchFileType.Content.toString())) {
            // TODO fix this 'content' regex. (NAS-1394)
            regex += Constants.REGEX_CONTENT;
        } else {
            regex += Constants.REGEX_ALL;
        }

        // validate the regular expression (throws exception if wrong).
        Pattern.compile(regex);

        Replica rep = Replica.getReplicaFromName(repName);

        new BatchExecuter(batchjob, regex, rep).start();

        JspWriter out = context.getOut();
        out.write("Executing batchjob with the following parameters. " + "<br/>\n");
        out.write("BatchJob name: " + jobName + "<br/>\n");
        out.write("Replica: " + rep.getName() + "<br/>\n");
        out.write("Regular expression: " + regex + "<br/>\n");
    } catch (Exception e) {
        throw new IOFailure("Could not instantiate the batchjob.", e);
    }
}

From source file:lucee.runtime.reflection.storage.WeakConstructorStorage.java

/**
 * seperate and store the different arguments of one constructor
 * @param constructor//from w ww .ja  va 2  s .  c  o  m
 * @param conArgs
 */
private void storeArgs(Constructor constructor, Array conArgs) {
    Class[] pmt = constructor.getParameterTypes();
    Object o = conArgs.get(pmt.length + 1, null);
    Constructor[] args;
    if (o == null) {
        args = new Constructor[1];
        conArgs.setEL(pmt.length + 1, args);
    } else {
        Constructor[] cs = (Constructor[]) o;
        args = new Constructor[cs.length + 1];
        for (int i = 0; i < cs.length; i++) {
            args[i] = cs[i];
        }
        conArgs.setEL(pmt.length + 1, args);
    }
    args[args.length - 1] = constructor;

}

From source file:it.unibas.spicy.persistence.object.operators.GenerateClassModelTree.java

private boolean isConstructorNoArgAvailable(Class currentClass) {
    Constructor[] constructors = currentClass.getConstructors();
    for (Constructor constructor : constructors) {
        if (constructor.getParameterTypes().length == 0) {
            return true;
        }/*from   w w w. j a v a2 s.  c  o  m*/
    }
    return false;
}

From source file:org.eurekastreams.commons.reflection.ReflectiveInstantiator.java

/**
 * Instantiate an object of the input class type with the empty constructor.
 * Private constructors are handled.//ww  w  .j ava2s .com
 *
 * @param objType
 *            the type of class to instantiate.
 *
 * @return an object of the input class type.
 */
public Object instantiateObject(final Class<?> objType) {
    Constructor<?> emptyConstructor = null;
    for (Constructor<?> constructor : objType.getDeclaredConstructors()) {
        if (constructor.getParameterTypes().length == 0) {
            emptyConstructor = constructor;
            break;
        }
    }
    if (emptyConstructor == null) {
        String message = "Cannot find empty constructor for " + objType.getName();
        log.error(message);
        throw new RuntimeException(message);
    }

    // set it accessible, just in case
    emptyConstructor.setAccessible(true);

    Object obj = null;
    try {
        obj = emptyConstructor.newInstance(new Object[0]);
    } catch (Exception e) {
        String message = "Couldn't instantiate: " + objType.getName();
        log.error(message, e);
        throw new RuntimeException(message);
    }

    return obj;
}

From source file:com.sm.query.utils.QueryUtils.java

public static Object createInstance(Class<?> cls) throws Exception {
    Constructor<?> constructor = null;
    Object[] constructorArgs = null;
    Constructor<?>[] constructors = cls.getDeclaredConstructors();
    //take the first constructor
    if (constructors.length > 0) {
        constructor = constructors[0];//from   w ww. ja v a2s.co m
        constructor.setAccessible(true);
        Class<?>[] params = constructor.getParameterTypes();
        constructorArgs = new Object[params.length];
        for (int i = 0; i < params.length; i++) {
            constructorArgs[i] = getParamArg(params[i]);
        }
        return constructor.newInstance(constructorArgs);
    } else
        return cls.newInstance();
}

From source file:com.opengamma.masterdb.security.SecurityTestCase.java

private static <T> Collection<T> permuteTestObjects(final Class<T> clazz, final Constructor<T> constructor) {
    final Collection<T> objects = new LinkedList<T>();
    final Class<?>[] parameters = constructor.getParameterTypes();
    final List<?>[] parameterValues = new List<?>[parameters.length];
    final int[] parameterIndex = new int[parameters.length];
    int longest = 0;
    for (int i = 0; i < parameters.length; i++) {
        parameterValues[i] = getTestObjects(parameters[i], clazz);
        if (parameterValues[i].size() > longest) {
            longest = parameterValues[i].size();
        }/*  w  ww . j  a v  a  2 s  . c  o m*/
    }
    final Object[] construct = new Object[parameters.length];
    final List<Throwable> exceptions = new LinkedList<Throwable>();
    // TODO: what about nulls ?
    for (int i = 0; i < longest; i++) {
        for (int j = 0; j < parameters.length; j++) {
            construct[j] = parameterValues[j].get(parameterIndex[j]);
            parameterIndex[j] = (parameterIndex[j] + 1) % parameterValues[j].size();
        }
        try {
            objects.add(constructor.newInstance(construct));
        } catch (final Throwable t) {
            exceptions.add(t);
        }
    }
    if (objects.size() == 0) {
        for (final Throwable t : exceptions) {
            t.printStackTrace();
        }
        throw new IllegalArgumentException("couldn't create test objects");
    }
    s_logger.info("{} objects created for {}", objects.size(), clazz);
    for (final Object o : objects) {
        s_logger.debug("{}", o);
    }
    return objects;
}

From source file:net.joala.junit.DefaultParameterizedParametersBuilder.java

private void validateClass() {
    final RunWith runWith = testClass.getAnnotation(RunWith.class);
    if (runWith == null) {
        throw new ParameterizedTestMismatchException(format("Test %s has no @RunWith annotation.", testName));
    }//from   w w  w  .  ja  va2 s  . co m
    final Class<? extends Runner> runner = runWith.value();
    if (!Parameterized.class.isAssignableFrom(runner)) {
        throw new ParameterizedTestMismatchException(format("Test %s is not marked with expected runner %s.",
                testName, Parameterized.class.getName()));
    }
    final Constructor<?>[] constructors = testClass.getConstructors();
    if (constructors.length == 0) {
        throw new ParameterizedTestMismatchException(
                format("%s misses constructor to receive parameter values.", testName));
    }
    if (constructors.length > 1) {
        throw new ParameterizedTestMismatchException(
                format("%s must not have more than one constructor", testName));
    }
    final Constructor<?> constructor = constructors[0];
    parameterTypes = constructor.getParameterTypes();
}

From source file:org.jabsorb.client.AccessibleObjectResolverTestCase.java

public void testResolution() {
    JSONArray args = new JSONArray();
    args.put(1);/*from   w  w  w . j  a  v a2s.  c  o m*/
    Constructor methodInt = (Constructor) resolver.resolveMethod(methodMap, "$constructor", args, serializer);
    Class[] params = methodInt.getParameterTypes();
    assertNotNull(params);
    assertEquals(1, params.length);
    assertEquals(Integer.TYPE, params[0]);
}

From source file:com.threewks.thundr.introspection.ClassIntrospector.java

@SuppressWarnings({ "rawtypes" })
public <T> List<Constructor<T>> listConstructors(Class<T> type) {
    ClassDescriptor classDescriptor = new ClassDescriptor(type, true);
    CollectionTransformer<Constructor, Constructor<T>> castAll = Expressive.Transformers
            .transformAllUsing(ClassIntrospector.<Constructor, Constructor<T>>castTransformer());
    List<Constructor<T>> ctors = castAll.from(classDescriptor.getAllCtors(true));
    Collections.sort(ctors, new Comparator<Constructor<T>>() {
        @Override//from w  w w . j a v a  2  s  .  c o m
        public int compare(Constructor<T> o1, Constructor<T> o2) {
            Class<?>[] types1 = o1.getParameterTypes();
            Class<?>[] types2 = o2.getParameterTypes();
            int compare = new Integer(types1.length).compareTo(types2.length);
            if (compare == 0) {
                // to keep the outcome consistent, we want to deterministically sort
                for (int i = 0; compare == 0 && i < types1.length; i++) {
                    compare = types1[i].getName().compareTo(types2[i].getName());
                }
            }
            return compare;
        }
    });
    return ctors;
}

From source file:jetbrains.buildServer.server.rest.util.BeanFactory.java

@Nullable
private <T> Constructor<T> findConstructor(@NotNull final Class<T> clazz, Class<?>[] argTypes) {
    try {/*from  w  w w.j av  a 2 s  . c o m*/
        return clazz.getConstructor(argTypes);
    } catch (NoSuchMethodException e) {
        //NOP
    }

    for (Constructor c : clazz.getConstructors()) {
        final Class[] reqTypes = c.getParameterTypes();
        if (checkParametersMatch(argTypes, reqTypes)) {
            //noinspection unchecked
            return (Constructor<T>) c;
        }
    }
    return null;
}