Example usage for java.lang Class getDeclaredConstructor

List of usage examples for java.lang Class getDeclaredConstructor

Introduction

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

Prototype

@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

Usage

From source file:org.leo.benchmark.Benchmark.java

/**
 * Run the benchmark on the given collection
 * /*from ww  w. j  a v  a 2 s .c o  m*/
 * @param collectionTested the collection (if it's a List, some additional
 *            bench will be done)
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void run(Class<? extends Collection> collectionClass) {
    try {
        long startTime = System.currentTimeMillis();
        Constructor<? extends Collection> constructor = collectionClass
                .getDeclaredConstructor((Class<?>[]) null);
        constructor.setAccessible(true);
        collection = (Collection<String>) constructor.newInstance();
        System.out.println("Performances of " + collection.getClass().getCanonicalName() + " populated with "
                + populateSize + " elt(s)");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

        // some collection used in some benchmark cases
        final Collection<String> col = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            col.add(Integer.toString(i % 30));
        }

        // Collection benchmark
        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.add(Integer.toString(i % 29));
            }
        }, populateSize, "add " + populateSize + " elements");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.remove(Integer.toString(i));
            }
        }, Math.max(1, populateSize / 10),
                "remove " + Math.max(1, populateSize / 10) + " elements given Object");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.addAll(col);
            }
        }, Math.min(populateSize, 1000),
                "addAll " + Math.min(populateSize, 1000) + " times " + col.size() + " elements");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.contains(collection.size() - i - 1);
            }
        }, Math.min(populateSize, 1000), "contains " + Math.min(populateSize, 1000) + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.removeAll(col);
            }
        }, Math.min(populateSize, 10),
                "removeAll " + Math.min(populateSize, 10) + " times " + col.size() + " elements");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.iterator();
            }
        }, populateSize, "iterator " + populateSize + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.containsAll(col);
            }
        }, Math.min(populateSize, 5000), "containsAll " + Math.min(populateSize, 5000) + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.toArray();
            }
        }, Math.min(populateSize, 5000), "toArray " + Math.min(populateSize, 5000) + " times");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.clear();
            }
        }, 1, "clear");

        execute(new BenchRunnable() {
            @Override
            public void run(int i) {
                collection.retainAll(col);
            }
        }, Math.min(populateSize, 10), "retainAll " + Math.min(populateSize, 10) + " times");

        // List benchmark
        if (collection instanceof List) {
            list = (List<String>) collection;
            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.add((i), Integer.toString(i));
                }
            }, populateSize, "add at a given index " + populateSize + " elements");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.addAll((i), col);
                }
            }, Math.min(populateSize, 1000), "addAll " + Math.min(populateSize, 1000) + " times " + col.size()
                    + " elements at a given index");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.get(i);
                }
            }, Math.min(populateSize, 50000), "get " + Math.min(populateSize, 50000) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.indexOf(i);
                }
            }, Math.min(populateSize, 5000), "indexOf " + Math.min(populateSize, 5000) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.lastIndexOf(i);
                }
            }, Math.min(populateSize, 5000), "lastIndexOf " + Math.min(populateSize, 5000) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.set(i, Integer.toString(i % 29));
                }
            }, Math.max(1, populateSize), "set " + Math.max(1, populateSize) + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.subList(collection.size() / 4, collection.size() / 2);
                }
            }, populateSize, "subList on a " + (populateSize / 2 - populateSize / 4) + " elts sublist "
                    + populateSize + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.listIterator();
                }
            }, populateSize, "listIterator " + populateSize + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.listIterator(i);
                }
            }, populateSize, "listIterator at a given index " + populateSize + " times");

            execute(new BenchRunnable() {
                @Override
                public void run(int i) {
                    list.remove(list.size() / 2);
                }
            }, 10000, "remove " + 10000 + " elements given index (index=list.size()/2)");
        }

        System.out.println(
                "Benchmark done in " + ((double) (System.currentTimeMillis() - startTime)) / 1000 + "s");
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        // free memory
        collection.clear();
    } catch (Exception e) {
        System.err.println("Failed running benchmark on class " + collectionClass.getCanonicalName());
        e.printStackTrace();
    }
    collection = null;
    list = null;
    heavyGc();
}

From source file:org.pircbotx.ConfigurationTest.java

@Test(dataProvider = "fieldNamesDataProvider", dependsOnMethods = "containSameFieldsTest", description = "Make sure every getter in builder gets called when creating Configuration")
@SuppressWarnings("unchecked")
public void copyConstructorTest(Class containerClass, Class copiedClass, Object copiedOpject, String getterName)
        throws Exception {
    //Get the method that is going to be called
    final Method methodToCall = copiedClass.getDeclaredMethod(getterName);

    //Trip if method gets called
    final MutableBoolean isMethodCalled = new MutableBoolean(false);
    Object copiedObjectSpied = mock(copiedClass,
            withSettings().spiedInstance(copiedOpject).defaultAnswer(new Answer() {
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (invocation.getMethod().equals(methodToCall))
                        isMethodCalled.setValue(true);
                    return invocation.callRealMethod();
                }/*from w w w. j ava 2  s.c  o  m*/
            }));

    //Call and test
    containerClass.getDeclaredConstructor(copiedClass).newInstance(copiedObjectSpied);
    assertTrue(isMethodCalled.getValue(), "Getter " + getterName
            + " on Builder not called in constructor in class " + containerClass.getCanonicalName());
}

From source file:net.mojodna.sprout.SproutAutoLoaderPlugIn.java

@SuppressWarnings("unchecked")
private void loadAction(final Class bean) {
    final Annotation[] annotations = bean.getAnnotations();

    for (int i = 0; i < annotations.length; i++) {
        final Annotation a = annotations[i];
        final Class type = a.annotationType();

        if (type.equals(SproutAction.class)) {
            final SproutAction form = (SproutAction) a;
            final String path = form.path();
            final Class<ActionConfig> mappingClass = form.mappingClass();
            final String scope = form.scope();
            final String name = form.name();
            final boolean validate = form.validate();
            final String input = form.input();
            final SproutProperty[] properties = form.properties();
            final SproutForward[] forwards = form.forwards();
            ActionConfig actionConfig = null;

            try {
                Constructor<ActionConfig> constructor = mappingClass.getDeclaredConstructor(new Class[] {});

                actionConfig = constructor.newInstance(new Object[] {});
            } catch (NoSuchMethodException nsme) {
                log.error("Failed to create a new instance of " + mappingClass.toString() + ", "
                        + nsme.getMessage());
            } catch (InstantiationException ie) {
                log.error("Failed to create a new instance of " + mappingClass.toString() + ", "
                        + ie.getMessage());
            } catch (IllegalAccessException iae) {
                log.error("Failed to create a new instance of " + mappingClass.toString() + ", "
                        + iae.getMessage());
            } catch (InvocationTargetException ite) {
                log.error("Failed to create a new instance of " + mappingClass.toString() + ", "
                        + ite.getMessage());
            }/*  ww  w  .  ja  v  a2s  .  c o  m*/

            if (actionConfig != null) {
                actionConfig.setPath(path);
                actionConfig.setType(bean.getName());
                actionConfig.setScope(scope);
                actionConfig.setValidate(validate);

                if (name.length() > 0) {
                    actionConfig.setName(name);
                }
                if (input.length() > 0) {
                    actionConfig.setInput(input);
                }

                if (properties != null && properties.length > 0) {
                    Map actionConfigBeanMap = new BeanMap(actionConfig);

                    for (int j = 0; j < properties.length; j++) {
                        actionConfigBeanMap.put(properties[j].property(), properties[j].value());
                    }
                }

                if (forwards != null && forwards.length > 0) {
                    for (int j = 0; j < forwards.length; j++) {
                        String fcModule = forwards[j].module();

                        actionConfig.addForwardConfig(makeForward(forwards[j].name(), forwards[j].path(),
                                forwards[j].redirect(), fcModule.length() == 0 ? null : fcModule));
                    }
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("Action " + path + " -> " + bean.getName());
            }

            getModuleConfig().addActionConfig(actionConfig);
        }
    }
}

From source file:org.nuxeo.ecm.platform.forms.layout.service.WebLayoutManagerImpl.java

@Override
public WidgetTypeHandler getWidgetTypeHandler(TagConfig config, String typeCategory, String typeName)
        throws WidgetException {
    if (StringUtils.isBlank(typeCategory)) {
        typeCategory = getDefaultStoreCategory();
    }/* www  .j  av a2 s .  co m*/
    WidgetType type = getLayoutStore().getWidgetType(typeCategory, typeName);
    if (type == null) {
        return null;
    }
    WidgetTypeHandler handler;
    Class<?> klass = type.getWidgetTypeClass();
    if (klass == null) {
        // implicit handler is the "template" one
        handler = new TemplateWidgetTypeHandler(config);
    } else {
        try {
            Constructor<?> ctor = klass.getDeclaredConstructor(TagConfig.class);
            ctor.setAccessible(true);
            handler = (WidgetTypeHandler) ctor.newInstance(config);
        } catch (ReflectiveOperationException e) {
            log.error("Caught error when instanciating widget type handler", e);
            return null;
        }
    }
    handler.setProperties(type.getProperties());
    return handler;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * New instance./*from w  w w.ja v  a2s  .c o m*/
 * 
 * @param <T>
 *          the generic type
 * @param clazz
 *          the clazz
 * @param paramTypes
 *          the param types
 * @param arguments
 *          the arguments
 * @return the t
 */
public static <T> T newInstance(Class<T> clazz, Class<?>[] paramTypes, Object[] arguments) {
    T instance = null;

    try {
        // Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        Constructor<T> constructor = clazz.getDeclaredConstructor(paramTypes);
        boolean access = constructor.isAccessible();
        constructor.setAccessible(true);
        instance = constructor.newInstance(arguments);
        if (!access) {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        logger.error(e);
    }
    return instance;
}

From source file:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.java

@Override
@Nullable//w  ww .  j  a v  a 2 s .  c  om
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
        throws BeanCreationException {

    // Let's check for lookup methods here..
    if (!this.lookupMethodsChecked.contains(beanName)) {
        try {
            ReflectionUtils.doWithMethods(beanClass, method -> {
                Lookup lookup = method.getAnnotation(Lookup.class);
                if (lookup != null) {
                    Assert.state(beanFactory != null, "No BeanFactory available");
                    LookupOverride override = new LookupOverride(method, lookup.value());
                    try {
                        RootBeanDefinition mbd = (RootBeanDefinition) beanFactory
                                .getMergedBeanDefinition(beanName);
                        mbd.getMethodOverrides().addOverride(override);
                    } catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(beanName,
                                "Cannot apply @Lookup to beans without corresponding bean definition");
                    }
                }
            });
        } catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
        }
        this.lookupMethodsChecked.add(beanName);
    }

    // Quick check on the concurrent map first, with minimal locking.
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    if (candidateConstructors == null) {
        // Fully synchronized resolution now...
        synchronized (this.candidateConstructorsCache) {
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                Constructor<?>[] rawCandidates;
                try {
                    rawCandidates = beanClass.getDeclaredConstructors();
                } catch (Throwable ex) {
                    throw new BeanCreationException(beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName()
                                    + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed",
                            ex);
                }
                List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
                Constructor<?> requiredConstructor = null;
                Constructor<?> defaultConstructor = null;
                Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                int nonSyntheticConstructors = 0;
                for (Constructor<?> candidate : rawCandidates) {
                    if (!candidate.isSynthetic()) {
                        nonSyntheticConstructors++;
                    } else if (primaryConstructor != null) {
                        continue;
                    }
                    AnnotationAttributes ann = findAutowiredAnnotation(candidate);
                    if (ann == null) {
                        Class<?> userClass = ClassUtils.getUserClass(beanClass);
                        if (userClass != beanClass) {
                            try {
                                Constructor<?> superCtor = userClass
                                        .getDeclaredConstructor(candidate.getParameterTypes());
                                ann = findAutowiredAnnotation(superCtor);
                            } catch (NoSuchMethodException ex) {
                                // Simply proceed, no equivalent superclass constructor found...
                            }
                        }
                    }
                    if (ann != null) {
                        if (requiredConstructor != null) {
                            throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: "
                                    + candidate
                                    + ". Found constructor with 'required' Autowired annotation already: "
                                    + requiredConstructor);
                        }
                        boolean required = determineRequiredStatus(ann);
                        if (required) {
                            if (!candidates.isEmpty()) {
                                throw new BeanCreationException(beanName,
                                        "Invalid autowire-marked constructors: " + candidates
                                                + ". Found constructor with 'required' Autowired annotation: "
                                                + candidate);
                            }
                            requiredConstructor = candidate;
                        }
                        candidates.add(candidate);
                    } else if (candidate.getParameterCount() == 0) {
                        defaultConstructor = candidate;
                    }
                }
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    if (requiredConstructor == null) {
                        if (defaultConstructor != null) {
                            candidates.add(defaultConstructor);
                        } else if (candidates.size() == 1 && logger.isWarnEnabled()) {
                            logger.warn("Inconsistent constructor declaration on bean with name '" + beanName
                                    + "': single autowire-marked constructor flagged as optional - "
                                    + "this constructor is effectively required since there is no "
                                    + "default constructor to fall back to: " + candidates.get(0));
                        }
                    }
                    candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
                } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                    candidateConstructors = new Constructor<?>[] { rawCandidates[0] };
                } else if (nonSyntheticConstructors == 2 && primaryConstructor != null
                        && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor, defaultConstructor };
                } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor };
                } else {
                    candidateConstructors = new Constructor<?>[0];
                }
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) {
    Class<?> declaringClass = constructor.getDeclaringClass();
    Class<?> userClass = ClassUtils.getUserClass(declaringClass);
    if (userClass != declaringClass) {
        try {/*  w w w.  j ava2 s  .c o  m*/
            return userClass.getDeclaredConstructor(constructor.getParameterTypes());
        } catch (NoSuchMethodException ex) {
            // No equivalent constructor on user class (superclass)...
            // Let's proceed with the given constructor as we usually would.
        }
    }
    return constructor;
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private boolean hasServiceStarterConstructor(ClassLoader cl, String className) throws ClassNotFoundException {
    Class clazz = Class.forName(className, true, cl);
    log.log(Level.FINE, MessageNames.CLASSLOADER_IS,
            new Object[] { clazz.getName(), clazz.getClassLoader().toString() });

    // Get this through dynamic lookup becuase it won't be in the parent
    // classloader!
    Class lifeCycleClass = Class.forName(Strings.LIFECYCLE_CLASS, true, cl);
    try {/*  w w w .  ja  v  a  2  s  .c  om*/
        Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass });
        return true;
    } catch (NoSuchMethodException nsme) {
        return false;
    }
}

From source file:com.netspective.sparx.form.DialogContext.java

public String getAsXml() throws ParserConfigurationException, ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Document doc = getAsXmlDocument();

    // we use reflection so that org.apache.xml.serialize.* is not a package requirement
    // TODO: when DOM Level 3 is finalized, switch it over to Load/Save methods in that DOM3 spec

    Class serializerCls = Class.forName("org.apache.xml.serialize.XMLSerializer");
    Class outputFormatCls = Class.forName("org.apache.xml.serialize.OutputFormat");

    Constructor serialCons = serializerCls
            .getDeclaredConstructor(new Class[] { OutputStream.class, outputFormatCls });
    Constructor outputCons = outputFormatCls.getDeclaredConstructor(new Class[] { Document.class });

    OutputStream os = new java.io.ByteArrayOutputStream();

    Object outputFormat = outputCons.newInstance(new Object[] { doc });
    Method indenting = outputFormatCls.getMethod("setIndenting", new Class[] { boolean.class });
    indenting.invoke(outputFormat, new Object[] { new Boolean(true) });
    Method omitXmlDecl = outputFormatCls.getMethod("setOmitXMLDeclaration", new Class[] { boolean.class });
    omitXmlDecl.invoke(outputFormat, new Object[] { new Boolean(true) });

    Object serializer = serialCons.newInstance(new Object[] { os, outputFormat });
    Method serialize = serializerCls.getMethod("serialize", new Class[] { Document.class });
    serialize.invoke(serializer, new Object[] { doc });

    return os.toString();
}

From source file:org.fluentlenium.core.Fluent.java

protected <T extends FluentPage> T constructPageWithParams(Class<T> cls, Object[] params)
        throws NoSuchMethodException, InstantiationException, IllegalAccessException,
        InvocationTargetException {
    T page;/*from  w w w . j  ava2 s  .c  o  m*/
    Class<?>[] classTypes = new Class[params.length];
    for (int i = 0; i < params.length; i++) {
        classTypes[i] = params[i].getClass();
    }

    try {
        Constructor<T> construct = cls.getDeclaredConstructor(classTypes);

        construct.setAccessible(true);
        page = construct.newInstance(params);
        return page;
    } catch (NoSuchMethodException ex) {
        if (params.length != 0) {
            throw new ConstructionException("You provided the wrong arguments to the createPage method, "
                    + "if you just want to use a page with a default constructor, use @Page or createPage("
                    + cls.getSimpleName() + ".class)", ex);
        } else {
            throw ex;
        }
    }
}