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:dinistiq.web.DinistiqContextLoaderListener.java

/**
 * Web related dinistiq initialization with parameters taken from the web.xml.
 *
 * Looks up relevant packages for scanning and a custom class resolver's implementation class name. Exposes any
 * bean from the dinistiq scope to the application scope (servlet context) of the web layer including an instance
 * of dinistiq itself./*from   w  w  w . j  a va2 s  .  c om*/
 *
 * @param contextEvent
 */
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    // just to check what our log instance looks like
    LOG.warn("contextInitialized() log: {}", LOG.getClass().getName());
    ServletContext context = contextEvent.getServletContext();
    Set<String> packages = new HashSet<>();
    String packagNameString = context.getInitParameter(DINISTIQ_PACKAGES);
    if (StringUtils.isNotBlank(packagNameString)) {
        for (String packageName : packagNameString.split(",")) {
            packageName = packageName.trim();
            packages.add(packageName);
        } // for
    } // if
    String classResolverName = context.getInitParameter(DINISTIQ_CLASSRESOLVER);
    ClassResolver classResolver = null;
    if (StringUtils.isNotBlank(classResolverName)) {
        try {
            Class<?> forName = Class.forName(classResolverName);
            Object[] args = new Object[1];
            args[0] = packages;
            classResolver = (ClassResolver) forName.getConstructors()[0].newInstance(args);
        } catch (Exception e) {
            LOG.error("contextInitialized() cannot obtain custom class resolver", e);
        } // try/catch
    } // if
    LOG.info("contextInitialized() classResolver: {} :{}", classResolver, classResolverName);
    classResolver = (classResolver == null) ? new SimpleClassResolver(packages) : classResolver;
    try {
        Map<String, Object> externalBeans = new HashMap<>();
        externalBeans.put("servletContext", context);
        Dinistiq dinistiq = new Dinistiq(classResolver, externalBeans);
        context.setAttribute(DINISTIQ_INSTANCE, dinistiq);
        for (String name : dinistiq.getAllBeanNames()) {
            context.setAttribute(name, dinistiq.findBean(Object.class, name));
        } // for
        Collection<RegisterableServlet> servlets = dinistiq.findBeans(RegisterableServlet.class);
        List<RegisterableServlet> orderedServlets = new ArrayList<>(servlets.size());
        orderedServlets.addAll(servlets);
        Collections.sort(orderedServlets);
        LOG.debug("contextInitialized() servlets {}", orderedServlets);
        for (RegisterableServlet servlet : orderedServlets) {
            ServletRegistration registration = context.addServlet(servlet.getClass().getSimpleName(), servlet);
            for (String urlPattern : servlet.getUrlPatterns()) {
                LOG.debug("contextInitialized() * {}", urlPattern);
                registration.addMapping(urlPattern);
            } // for
        } // for
    } catch (Exception ex) {
        LOG.error("init()", ex);
    } // try/catch
}

From source file:org.ops4j.gaderian.service.impl.LoggingInterceptorFactory.java

private Object instantiateInterceptor(InterceptorStack stack, Class interceptorClass) throws Exception {
    Object stackTop = stack.peek();

    Constructor c = interceptorClass.getConstructors()[0];

    return c.newInstance(new Object[] { stack.getServiceLog(), stackTop });
}

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

@SuppressWarnings("unchecked")
private static <T> Constructor<T> findConstructor(Class<? extends T> clazz, int length) {
    try { // may work without this, but only if the JVM happens to return the right overload first
        if (clazz == ParametersDefinitionProperty.class && length == 1) { // TODO pending core fix
            return (Constructor<T>) ParametersDefinitionProperty.class.getConstructor(List.class);
        }//w w  w. j  a v a2 s.c o m
    } catch (NoSuchMethodException x) {
        throw new AssertionError(x);
    }
    Constructor<T>[] ctrs = (Constructor<T>[]) clazz.getConstructors();
    for (Constructor<T> c : ctrs) {
        if (c.getAnnotation(DataBoundConstructor.class) != null) {
            if (c.getParameterTypes().length != length) {
                throw new IllegalArgumentException(c
                        + " has @DataBoundConstructor but it doesn't match with your .stapler file. Try clean rebuild");
            }
            return c;
        }
    }
    for (Constructor<T> c : ctrs) {
        if (c.getParameterTypes().length == length) {
            return c;
        }
    }
    throw new IllegalArgumentException(clazz + " does not have a constructor with " + length + " arguments");
}

From source file:org.javaan.bytecode.ReflectionClassContextBuilder.java

private void addMethods(Type type, Class<?> clazz) {
    clazz.getMethods();//w ww.  j a  va  2s .  c o m
    for (java.lang.reflect.Method method : clazz.getDeclaredMethods()) {
        context.addMethod(Method.create(type, method));
    }
    for (Constructor<?> constructor : clazz.getConstructors()) {
        context.addMethod(Method.create(type, constructor));
    }
}

From source file:edu.brown.utils.ClassUtil.java

/**
 * Grab the constructor for the given target class with the provided input parameters.
 * This method will first try to find an exact match for the parameters, and if that
 * fails then it will be smart and try to find one with the input parameters super classes. 
 * @param <T>/*from  w w w.  j  av  a2 s  .  c om*/
 * @param target_class
 * @param params
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructor(Class<T> target_class, Class<?>... params) {
    NoSuchMethodException error = null;
    try {
        return (target_class.getConstructor(params));
    } catch (NoSuchMethodException ex) {
        // The first time we get this it can be ignored
        // We'll try to be nice and find a match for them
        error = ex;
    }
    assert (error != null);

    if (debug.val) {
        LOG.debug("TARGET CLASS:  " + target_class);
        LOG.debug("TARGET PARAMS: " + Arrays.toString(params));
    }

    final int num_params = (params != null ? params.length : 0);
    List<Class<?>> paramSuper[] = (List<Class<?>>[]) new List[num_params];
    for (int i = 0; i < num_params; i++) {
        paramSuper[i] = ClassUtil.getSuperClasses(params[i]);
        if (debug.val)
            LOG.debug("  SUPER[" + params[i].getSimpleName() + "] => " + paramSuper[i]);
    } // FOR

    for (Constructor<?> c : target_class.getConstructors()) {
        Class<?> cTypes[] = c.getParameterTypes();
        if (debug.val) {
            LOG.debug("CANDIDATE: " + c);
            LOG.debug("CANDIDATE PARAMS: " + Arrays.toString(cTypes));
        }
        if (params.length != cTypes.length)
            continue;

        for (int i = 0; i < num_params; i++) {
            List<Class<?>> cSuper = ClassUtil.getSuperClasses(cTypes[i]);
            if (debug.val)
                LOG.debug("  SUPER[" + cTypes[i].getSimpleName() + "] => " + cSuper);
            if (CollectionUtils.intersection(paramSuper[i], cSuper).isEmpty() == false) {
                return ((Constructor<T>) c);
            }
        } // FOR (param)
    } // FOR (constructors)
    throw new RuntimeException("Failed to retrieve constructor for " + target_class.getSimpleName(), error);
}

From source file:mangotiger.poker.channel.EventParserImpl.java

public void add(final Class<?> event, final String regex, final Type... groups) {
    final List<EventMatcher> valid = new LinkedList<EventMatcher>();
    final List<EventMatcher> invalid = new LinkedList<EventMatcher>();
    for (Constructor<?> constructor : event.getConstructors()) {
        final EventMatcher eventMatcher = new EventMatcherImpl(constructor, regex, groups);
        if (eventMatcher.isValid()) {
            valid.add(eventMatcher);/* w  w w .  j a v  a2s  .  c  om*/
        } else {
            invalid.add(eventMatcher);
        }
    }
    if (valid.size() > 1)
        log().warn("duplicate constructors match, using first one: " + valid);
    if (valid.size() > 0) {
        eventMatchers.add(valid.get(0));
    } else {
        final StringBuilder message = new StringBuilder("no matching constructor found:");
        for (EventMatcher eventMatcher : invalid) {
            message.append("\n\t").append(eventMatcher);
        }
        throw new IllegalArgumentException(message.toString());
    }
}

From source file:org.lenskit.eval.traintest.metrics.MetricLoaderHelper.java

@Nullable
public <T> T createMetric(Class<T> type, JsonNode node) {
    String typeName = getMetricTypeName(node);
    if (typeName == null) {
        return null;
    }//ww  w .j a  v  a2  s  .  c  om
    if (!node.isObject()) {
        node = JsonNodeFactory.instance.objectNode().set("type", node);
    }

    Class<?> metric = findClass(typeName);
    if (metric == null) {
        logger.warn("could not find metric {} for ", typeName, type);
        return null;
    }
    for (Constructor<?> ctor : metric.getConstructors()) {
        if (ctor.getAnnotation(JsonCreator.class) != null) {
            return type.cast(SpecUtils.createMapper().convertValue(node, metric));
        }
    }

    // ok, just instantiate
    try {
        return type.cast(metric.newInstance());
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("Cannot instantiate " + metric, e);
    }
}

From source file:org.unitils.core.context.Context.java

protected Constructor<?> getConstructor(Class<?> implementationType) {
    Constructor<?>[] constructors = implementationType.getConstructors();
    // use default constructor if there are no constructors
    if (constructors.length == 0) {
        return null;
    }//ww  w  .  j av  a2s .com
    // try no-args constructor if there is more than one constructor
    if (constructors.length > 1) {
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterTypes().length == 0) {
                return null;
            }
        }
        throw new UnitilsException(
                "Found more than 1 constructor in implementation type " + implementationType.getName());
    }
    return constructors[0];
}

From source file:edu.wustl.bulkoperator.action.BulkHandler.java

/**
 * This method will be called to get fileItem.
 * @param fileItem fileItem/*ww w .ja v  a2s . c  o  m*/
 * @return FormFile FormFile
 * @throws BulkOperationException BulkOperationException
 */
public FormFile getFormFile(FileItem fileItem) throws BulkOperationException {
    try {
        Class parentClass = Class.forName("org.apache.struts.upload.CommonsMultipartRequestHandler");

        Class childClass = parentClass.getDeclaredClasses()[0];
        Constructor constructor = childClass.getConstructors()[0];
        constructor.setAccessible(true);
        return (FormFile) constructor.newInstance(new Object[] { fileItem });
    } catch (Exception exp) {
        ErrorKey errorkey = ErrorKey.getErrorKey("bulk.operation.request.param.error");
        throw new BulkOperationException(errorkey, exp, "");
    }
}

From source file:net.abhinavsarkar.spelhelper.SpelHelper.java

/**
 * Registers the public constructors of the class `clazz` so that they
 * can be called by their simple name from SpEL expressions.
 * @param clazz The class to register the constructors from.
 * @return      The current instance of SpelHelper. This is for chaining
 * the methods calls./*from  w w  w. j a v  a  2 s  .  c o m*/
 */
public SpelHelper registerConstructorsFromClass(final Class<?> clazz) {
    for (Constructor<?> constructor : asList(clazz.getConstructors())) {
        registeredConstructors.put(constructor.getDeclaringClass().getSimpleName()
                + Arrays.toString(constructor.getParameterTypes()), constructor);
    }
    return this;
}