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:se.vgregion.portal.innovatinosslussen.domain.TypesBeanTest.java

void doGetterSetterValuesMatch(Class... typeInPackage)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    for (Class item : typeInPackage)
        for (Class type : getTypes(item)) {
            if (!type.isEnum()) {
                if (type.getDeclaredConstructors()[0].getModifiers() == Modifier.PUBLIC) {
                    doGetterSetterValuesMatch(type.newInstance());
                }//w w w  . jav a 2  s.com
            }
        }
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Find constructor./* w w w .j  av a  2 s .co  m*/
 *
 * @param <T> the generic type
 * @param clazz the clazz
 * @param args the args
 * @return the constructor
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> clazz, Object[] args) {
    nextMethod: for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {

        Class<?>[] argClazzes = constructor.getParameterTypes();
        if (argClazzes.length != args.length) {
            continue;
        }
        for (int i = 0; i < args.length; ++i) {
            Object a = args[i];
            Class<?> ac = argClazzes[i];
            if (a != null && ac.isAssignableFrom(a.getClass()) == false) {
                continue nextMethod;
            }
        }
        return (Constructor<T>) constructor;
    }
    return null;
}

From source file:org.jnosql.artemis.reflection.Reflections.java

/**
 * Make the given a constructor class accessible, explicitly setting it accessible
 * if necessary. The setAccessible(true) method is only
 * called when actually necessary, to avoid unnecessary
 * conflicts with a JVM SecurityManager (if active).
 *
 * @param clazz the class constructor acessible
 * @throws ConstructorException when the constructor has public and default
 *//*from   ww w .j  a v  a 2  s  . com*/
public Constructor makeAccessible(Class clazz) throws ConstructorException {
    List<Constructor> constructors = Stream.of(clazz.getDeclaredConstructors())
            .filter(c -> c.getParameterCount() == 0).collect(toList());

    if (constructors.isEmpty()) {
        throw new ConstructorException(clazz);
    }
    Optional<Constructor> publicConstructor = constructors.stream()
            .filter(c -> Modifier.isPublic(c.getModifiers())).findFirst();
    if (publicConstructor.isPresent()) {
        return publicConstructor.get();
    }

    Constructor constructor = constructors.get(0);
    constructor.setAccessible(true);
    return constructor;
}

From source file:gda.factory.corba.util.ImplFactory.java

protected void makeObjectsAvailable() throws FactoryException {
    POA poa = netService.getPOA();

    //TODO All errors should lead to throwing a FactoryException - check error then lead to system exit
    org.omg.PortableServer.Servant servant;

    Runtime.getRuntime().addShutdownHook(uk.ac.gda.util.ThreadManager.getThread(new Runnable() {
        @Override//  ww  w  . java 2  s .  c om
        public void run() {
            shutdown();
        }
    }, getNamespace() + " ImplFactory shutdown"));

    List<Findable> findables = getFindablesToMakeAvailable();
    for (Findable findable : findables) {
        String name = findable.getName();
        if (findable instanceof Localizable && !((Localizable) findable).isLocal()) {

            if (excludedObjects != null && excludedObjects.contains(name)) {
                logger.info(String.format("Not exporting %s - it has been excluded", name));
                continue;
            }

            Class<?> type = findable.getClass();
            if (RbacUtils.objectIsCglibProxy(findable)) {
                // Object has been proxied. Get its original type
                type = type.getSuperclass();
            }

            String implName = CorbaUtils.getImplementationClassName(type);
            String adapterClassName = CorbaUtils.getAdapterClassName(type);

            org.omg.CORBA.Object obj = null;
            try {
                Class<?> classDef = Class.forName(implName);
                Constructor<?>[] ctors = classDef.getDeclaredConstructors();
                Constructor<?> ctor = ctors[0];

                final Object[] args = new Object[] { findable, poa };
                if (!ClassUtils.isAssignable(ClassUtils.toClass(args), ctor.getParameterTypes())) {
                    logger.warn("Class " + implName + " is unsuitable for " + name
                            + ", so it will be a local object");
                }

                else {
                    servant = (org.omg.PortableServer.Servant) ctor.newInstance(args);
                    obj = poa.servant_to_reference(servant);
                }
            } catch (ClassNotFoundException ex) {
                logger.warn("Cannot find class " + implName + ": " + name + " will be a local object");
            } catch (Exception e) {
                logger.error(
                        "Could not instantiate class " + implName + ": " + name + " will be a local object", e);
            }

            String fullName = getNamespace() + NetService.OBJECT_DELIMITER + name;
            if (obj != null) {
                // bind throws a factory exception which is not caught
                // but passed back to the caller.
                store.put(fullName, new CorbaBoundObject(fullName, adapterClassName, obj));
                netService.bind(fullName, adapterClassName, obj);
                logger.debug("ImplFactory created Corba object for " + fullName);
            } else {
                logger.warn("No CORBA object created for " + fullName);
            }
        }

        else {
            logger.debug(
                    String.format("Not exporting %s - it is local (or does not implement Localizable)", name));
        }
    }
}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Gets the declared members of the given type from the specified class.
 *
 * @author paouelle//from  w  w  w.  j  ava 2s  .com
 *
 * @param <T> the type of member
 *
 * @param  type the type of members to retrieve
 * @param  clazz the class from which to retrieve the members
 * @return the non-<code>null</code> members of the given type from the
 *         specified class
 * @throws NullPointerException if <code>type</code> or
 *         <code>clazz</code> is <code>null</code>
 * @throws IllegalArgumentException if <code>type</code> is not
 *         {@link Field}, {@link Method}, or {@link Constructor}
 */
@SuppressWarnings("unchecked")
public static <T extends Member> T[] getDeclaredMembers(Class<T> type, Class<?> clazz) {
    org.apache.commons.lang3.Validate.notNull(type, "invalid null member type");
    org.apache.commons.lang3.Validate.notNull(clazz, "invalid null class");
    if (type == Field.class) {
        return (T[]) clazz.getDeclaredFields();
    } else if (type == Method.class) {
        return (T[]) clazz.getDeclaredMethods();
    } else if (type == Constructor.class) {
        return (T[]) clazz.getDeclaredConstructors();
    } else {
        throw new IllegalArgumentException("invalid member class: " + type.getName());
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

/**
 * Returns a {@link Constructor} object that reflects the specified constructor of the given type.
 * <p/>/* w ww. ja v  a2s .c  o m*/
 * If no parameter types are specified i.e., {@code paramTypes} is {@code null} or empty, the default constructor
 * is returned.<br/>
 * If a parameter type is not known i.e., it is {@code null}, all declared constructors are checked whether their
 * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter
 * type of the constructor and if exactly one was found, it is returned.<br/>
 * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several constructors were found.
 *
 * @param type the class
 * @param paramTypes the full-qualified class names of the parameters (can be {@code null})
 * @param classLoader the class loader to use
 * @return the accessible constructor resolved
 * @throws NoSuchMethodException if there are zero or more than one constructor candidates
 * @throws ClassNotFoundException if a class cannot be located by the specified class loader
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... clazzes)
        throws NoSuchMethodException, ClassNotFoundException {
    Constructor<T> constructor = null;

    // If all parameter types are known, find the constructor that exactly matches the signature
    if (!ArrayUtils.contains(clazzes, null)) {
        try {
            constructor = type.getDeclaredConstructor(clazzes);
        } catch (NoSuchMethodException e) {
            // Ignore
        }
    }

    // If no constructor was found, find all possible candidates
    if (constructor == null) {
        List<Constructor<T>> candidates = new ArrayList<>(1);
        for (Constructor<T> declaredConstructor : (Constructor<T>[]) type.getDeclaredConstructors()) {
            if (ClassUtils.isAssignable(clazzes, declaredConstructor.getParameterTypes())) {

                // Check if there is already a constructor method with the same signature
                for (int i = 0; i < candidates.size(); i++) {
                    Constructor<T> candidate = candidates.get(i);
                    /**
                     * If all parameter types of constructor A are assignable to the types of constructor B
                     * (at least one type is a subtype of the corresponding parameter), keep the one whose types
                     * are more concrete and drop the other one.
                     */
                    if (ClassUtils.isAssignable(declaredConstructor.getParameterTypes(),
                            candidate.getParameterTypes())) {
                        candidates.remove(candidate);
                        i--;
                    } else if (ClassUtils.isAssignable(candidate.getParameterTypes(),
                            declaredConstructor.getParameterTypes())) {
                        declaredConstructor = null;
                        break;
                    }
                }

                if (declaredConstructor != null) {
                    candidates.add(declaredConstructor);
                }
            }
        }
        if (candidates.size() != 1) {
            throw new NoSuchMethodException(
                    String.format("Cannot find distinct constructor for type '%s' with parameter types %s",
                            type, Arrays.toString(clazzes)));
        }
        constructor = candidates.get(0);
    }

    //do we really need this dependency?
    //ReflectionUtils.makeAccessible(constructor);
    if (constructor != null && !constructor.isAccessible())
        constructor.setAccessible(true);

    return constructor;

}

From source file:hu.bme.mit.sette.common.validator.reflection.ClassValidator.java

/**
 * Sets the required declared constructor count for the Java class.
 *
 * @param declCtorCount/* w ww  .  j  a v a 2s.  c o m*/
 *            the required declared constructor count for the Java class.
 * @return this object
 */
public ClassValidator declaredConstructorCount(final int declCtorCount) {
    Validate.isTrue(declCtorCount >= 0,
            "The required declared constructor count must be " + "a non-negative number");

    if (getSubject() != null) {
        Class<?> javaClass = getSubject();

        if (javaClass.getDeclaredConstructors().length != declCtorCount) {
            if (declCtorCount == 0) {
                this.addException("The Java class must not have " + "any declared constructors");
            } else if (declCtorCount == 1) {
                this.addException("The Java class must have " + "exactly 1 declared constructor");
            } else {
                this.addException(String.format(
                        "The Java class must have " + "exactly %d declared constructors", declCtorCount));
            }
        }
    }

    return this;
}

From source file:org.pircbotx.hooks.events.MassEventTest.java

@Test(dependsOnMethods = "singleConstructorTest", dataProvider = "eventObjectDataProvider", dataProviderClass = TestUtils.class, description = "Verify number of class fields and number of constructor params match")
public void constructorParamToFieldTest(Class<?> event) {
    if (event == WhoisEvent.class) {
        //This uses a builder
        return;/*from   w w w.j a v a  2 s  . c o m*/
    }

    //Manually count fields to exclude synthetic ones
    int fieldCount = 0;
    for (Field curField : event.getDeclaredFields())
        if (TestUtils.isRealMember(curField))
            fieldCount++;
    Constructor constructor = event.getDeclaredConstructors()[0];
    //(subtract one parameter to account for bot)
    assertEquals(constructor.getParameterTypes().length - 1, fieldCount,
            wrapClass(event,
                    "Number of constructor parameters don't match number of fields" + SystemUtils.LINE_SEPARATOR
                            + "Constructor params [" + StringUtils.join(constructor.getParameterTypes(), ", ")
                            + "]"));
}

From source file:org.datalorax.populace.core.populate.instance.DefaultConstructorInstanceFactory.java

private <T> Constructor<? extends T> getConstructor(final Class<? extends T> rawType,
        Class<?>... parameterTypes) {
    try {/*from ww  w .  j  ava2 s. c  o m*/
        final Constructor<? extends T> defaultConstructor = rawType.getDeclaredConstructor(parameterTypes);
        defaultConstructor.setAccessible(true);
        return defaultConstructor;
    } catch (NoSuchMethodException e) {
        final Constructor<?>[] constructors = rawType.getDeclaredConstructors();
        throw new PopulatorException(
                "Failed to instantiate type as no viable constructor could be found for type."
                        + " Either add a suitable constructor or consider adding a custom InstanceFactory to handle this type."
                        + "\n\tType: " + rawType + "\n\tRequired constructor arguments: "
                        + (parameterTypes.length == 0 ? "none" : StringUtils.join(parameterTypes, ','))
                        + "\n\tavailable Constructors: "
                        + (constructors.length == 0 ? "none" : StringUtils.join(constructors, ',')),
                e);
    }
}

From source file:ShowClass.java

/**
 * Display the modifiers, name, superclass and interfaces of a class or
 * interface. Then go and list all constructors, fields, and methods.
 *//*from www .  jav a  2 s. c o m*/
public static void print_class(Class c) {
    // Print modifiers, type (class or interface), name and superclass.
    if (c.isInterface()) {
        // The modifiers will include the "interface" keyword here...
        System.out.print(Modifier.toString(c.getModifiers()) + " " + typename(c));
    } else if (c.getSuperclass() != null) {
        System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c) + " extends "
                + typename(c.getSuperclass()));
    } else {
        System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c));
    }

    // Print interfaces or super-interfaces of the class or interface.
    Class[] interfaces = c.getInterfaces();
    if ((interfaces != null) && (interfaces.length > 0)) {
        if (c.isInterface())
            System.out.print(" extends ");
        else
            System.out.print(" implements ");
        for (int i = 0; i < interfaces.length; i++) {
            if (i > 0)
                System.out.print(", ");
            System.out.print(typename(interfaces[i]));
        }
    }

    System.out.println(" {"); // Begin class member listing.

    // Now look up and display the members of the class.
    System.out.println("  // Constructors");
    Constructor[] constructors = c.getDeclaredConstructors();
    for (int i = 0; i < constructors.length; i++)
        // Display constructors.
        print_method_or_constructor(constructors[i]);

    System.out.println("  // Fields");
    Field[] fields = c.getDeclaredFields(); // Look up fields.
    for (int i = 0; i < fields.length; i++)
        // Display them.
        print_field(fields[i]);

    System.out.println("  // Methods");
    Method[] methods = c.getDeclaredMethods(); // Look up methods.
    for (int i = 0; i < methods.length; i++)
        // Display them.
        print_method_or_constructor(methods[i]);

    System.out.println("}"); // End class member listing.
}