Example usage for java.lang Class getDeclaredConstructors

List of usage examples for java.lang Class getDeclaredConstructors

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.openehealth.ipf.commons.lbs.utils.NiceClass.java

/**
 * Ensures that a utility class (i.e. a class with only static methods) cannot be 
 * instantiated//from   w ww.  j a v a2s.  c o  m
 * @param utilityClass
 *          the class to test
 * @throws Exception
 *          any unexpected exception that occurred 
 */
public static void checkUtilityClass(Class<?> utilityClass) throws Exception {
    Constructor<?>[] constructors = utilityClass.getDeclaredConstructors();
    assertEquals(1, constructors.length);
    assertTrue(Modifier.isPrivate(constructors[0].getModifiers()));
    constructors[0].setAccessible(true);
    try {
        constructors[0].newInstance(new Object[] {});
        fail("Expected Exception: " + InvocationTargetException.class.getSimpleName());
    } catch (InvocationTargetException e) {
        // That's expected
    }
}

From source file:org.apache.drill.jdbc.ITTestShadedJar.java

private static void runWithLoader(String name, ClassLoader loader) throws Exception {
    Class<?> clazz = loader.loadClass(ITTestShadedJar.class.getName() + "$" + name);
    Object o = clazz.getDeclaredConstructors()[0].newInstance(loader);
    clazz.getMethod("go").invoke(o);
}

From source file:uk.org.lidalia.sysoutslf4j.integration.CrossClassLoaderTestUtils.java

@SuppressWarnings("unchecked")
private static <E> E createProxyClass(Class<E> classToProxy, ReflectionInvocationHandler handler) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass(classToProxy);
    try {//  w  w w.  j a v a  2 s. co m
        return (E) proxyFactory.create(classToProxy.getDeclaredConstructors()[0].getParameterTypes(),
                new Object[classToProxy.getDeclaredConstructors()[0].getParameterTypes().length], handler);
    } catch (Exception e) {
        Exceptions.throwUnchecked(e);
        throw new AssertionError("Unreachable");
    }
}

From source file:org.openehealth.ipf.commons.lbs.utils.NiceClass.java

/**
 * Ensures that all constructors of a class are null safe.
 * <p>//from   w  w w . ja  va2 s .c o  m
 * Test involves public constructors.
 * @param obj
 *          object to test
 * @param args
 *          dummy arguments of all different parameter types that any of the constructors have
 * @param optional
 *          optional dummy arguments that can also be set to {@code null} without breaking
 *          null-safety
 * @throws any thrown exception that were not expected. Never an {@link IllegalArgumentException}.
 */
public static void checkConstructorsAreNullSafe(Class<?> clazz, List<?> args, List<?> optional)
        throws Exception {
    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        if (Modifier.isPublic(constructor.getModifiers())) {
            checkConstructorIsNullSafe(constructor, args, optional);
        }
    }
}

From source file:se.trillian.goodies.spring.DomainObjectFactoryFactoryBean.java

private static Constructor<?> findMatchingConstructor(Class<?> clazz, Method m) {
    LinkedList<Constructor<?>> constructors = new LinkedList<Constructor<?>>();
    Constructor<?> directMatch = null;
    for (Constructor<?> c : clazz.getDeclaredConstructors()) {
        if (isParameterTypesPrefix(m.getParameterTypes(), c.getParameterTypes())) {
            constructors.add(c);/* ww  w  .  j a  v a  2  s . co m*/
            if (directMatch == null && isParameterTypesPrefix(c.getParameterTypes(), m.getParameterTypes())) {
                directMatch = c;
            }
        }
    }
    if (constructors.isEmpty()) {
        throw new IllegalArgumentException("No matching constructor found in " + "implementation class '"
                + clazz + "' for factory method '" + m + "'");
    }
    if (constructors.size() > 1) {
        if (directMatch != null) {
            return directMatch;
        }
        throw new IllegalArgumentException("More than 1 matching constructor "
                + "found in implementation class '" + clazz + "' for factory method '" + m + "'");
    }
    return constructors.getFirst();
}

From source file:ReflectApp.java

static void describeClassOrInterface(Class className, String name) {
    displayModifiers(className.getModifiers());
    displayFields(className.getDeclaredFields());
    displayMethods(className.getDeclaredMethods());

    if (className.isInterface()) {
        System.out.println("Interface: " + name);
    } else {/*from www. jav  a  2s.c om*/
        System.out.println("Class: " + name);
        displayInterfaces(className.getInterfaces());
        displayConstructors(className.getDeclaredConstructors());
    }
}

From source file:org.grouplens.grapht.util.ClassProxy.java

private static void checksumClass(Class<?> type, MessageDigest digest) {
    // we compute a big hash of all the members of the class, and its superclasses.

    List<String> members = new ArrayList<String>();
    for (Constructor<?> c : type.getDeclaredConstructors()) {
        if (isInjectionSensitive(c)) {
            members.add(String.format("%s(%s)", c.getName(), StringUtils.join(c.getParameterTypes(), ", ")));
        }/*from w  ww .  j  a va  2s . c om*/
    }
    for (Method m : type.getDeclaredMethods()) {
        if (isInjectionSensitive(m)) {
            members.add(String.format("%s(%s): %s", m.getName(), StringUtils.join(m.getParameterTypes(), ", "),
                    m.getReturnType()));
        }
    }
    for (Field f : type.getDeclaredFields()) {
        if (isInjectionSensitive(f)) {
            members.add(f.getName() + ":" + f.getType().getName());
        }
    }

    Collections.sort(members);

    Class<?> sup = type.getSuperclass();
    if (sup != null) {
        checksumClass(sup, digest);
    }
    for (String mem : members) {
        digest.update(mem.getBytes(UTF8));
    }
}

From source file:co.jirm.mapper.definition.SqlParameterDefinition.java

static Map<String, SqlParameterDefinition> getSqlBeanParameters(Class<?> k, SqlObjectConfig config) {
    Map<String, SqlParameterDefinition> parameters = new LinkedHashMap<String, SqlParameterDefinition>();
    Constructor<?> cons[] = k.getDeclaredConstructors();
    for (Constructor<?> c : cons) {
        if (c.isAnnotationPresent(JsonCreator.class)) {
            return getSqlBeanParametersFromJsonCreatorConstructor(c, config);
        }//  www.j  a v  a  2 s . co m

        if (c.isAnnotationPresent(ConstructorProperties.class)) {
            return getSqlBeanParametersFromConstructorProperties(c, config);
        }
    }
    check.argument(!parameters.isEmpty(), "No SQL columns/parameters found for: {}", k);
    return parameters;
}

From source file:org.seedstack.seed.core.utils.BaseClassSpecifications.java

/**
 * @return a specification which check if a least one constructor is public
 *///from   www.j a  v  a  2 s . c o m
public static Specification<Class<?>> classConstructorIsPublic() {
    return new AbstractSpecification<Class<?>>() {
        @Override
        public boolean isSatisfiedBy(Class<?> candidate) {

            for (Constructor<?> constructor : candidate.getDeclaredConstructors()) {
                if (Modifier.isPublic(constructor.getModifiers())) {
                    return true;
                }
            }
            return false;
        }
    };
}

From source file:com.rockagen.commons.util.ClassUtil.java

/**
 * obtain constructor list of specified class If recursively is true, obtain
 * constructor from all class hierarchy/*from  ww w .  j ava 2s .c  o m*/
 * 
 * 
 * @param clazz class
 *            where fields are searching
 * @param recursively
 *            param
 * @return array of constructors
 */
public static Constructor<?>[] getDeclaredConstructors(Class<?> clazz, boolean recursively) {
    List<Constructor<?>> constructors = new LinkedList<Constructor<?>>();
    Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
    Collections.addAll(constructors, declaredConstructors);

    Class<?> superClass = clazz.getSuperclass();

    if (superClass != null && recursively) {
        Constructor<?>[] declaredConstructorsOfSuper = getDeclaredConstructors(superClass, true);
        if (declaredConstructorsOfSuper.length > 0)
            Collections.addAll(constructors, declaredConstructorsOfSuper);
    }
    return constructors.toArray(new Constructor<?>[constructors.size()]);
}