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:com.github.tomakehurst.wiremock.matching.StringValuePatternJsonDeserializer.java

@SuppressWarnings("unchecked")
private static Constructor<? extends StringValuePattern> findConstructor(
        Class<? extends StringValuePattern> clazz) {
    Optional<Constructor<?>> optionalConstructor = tryFind(asList(clazz.getDeclaredConstructors()),
            new Predicate<Constructor<?>>() {
                @Override/*  w  w  w. ja  v a 2 s  . co m*/
                public boolean apply(Constructor<?> input) {
                    return input.getParameterTypes().length == 1
                            && input.getGenericParameterTypes()[0].equals(String.class);
                }
            });

    if (!optionalConstructor.isPresent()) {
        throw new IllegalStateException(
                "Constructor for " + clazz.getSimpleName() + " must have a single string argument constructor");
    }

    return (Constructor<? extends StringValuePattern>) optionalConstructor.get();
}

From source file:com.edmunds.autotest.ClassUtil.java

public static Constructor getDefaultConstructor(Class cls) {
    final Constructor[] constructors = cls.getDeclaredConstructors();

    for (Constructor constructor : constructors) {
        if (constructor.getParameterTypes().length == 0) {
            return constructor;
        }/*  w w  w.  j  av a 2  s.  c  om*/
    }

    return null;
}

From source file:com.edmunds.autotest.ClassUtil.java

public static boolean hasDefaultConstructor(Class cls) {
    boolean defaultConstructor = false;

    final Constructor[] constructors = cls.getDeclaredConstructors();

    for (Constructor constructor : constructors) {
        if (constructor.getParameterTypes().length == 0) {
            defaultConstructor = true;//  w w  w  .j  av a  2 s  .  c  om
            break;
        }
    }
    return defaultConstructor;
}

From source file:org.lunarray.model.descriptor.creational.util.CreationalScanUtil.java

/**
 * Find a no-args public constructor./*from   w  ww . j  a  v  a 2  s.c om*/
 * 
 * @param source
 *            The source class. May not be null.
 * @return The constructor, or null.
 * @param <E>
 *            The entity type.
 */
@SuppressWarnings("unchecked")
public static <E> Constructor<E> findConstructor(final Class<E> source) {
    Validate.notNull(source, "Source may not be null.");
    Constructor<E> result = null;
    if (!Modifier.isAbstract(source.getModifiers()) && !source.isSynthetic()) {
        for (final Constructor<E> constructor : (Constructor<E>[]) source.getConstructors()) {
            if (!constructor.isSynthetic() && (constructor.getParameterTypes().length == 0)) {
                result = constructor;
            }
        }
    }
    return result;
}

From source file:ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.java

/**
 * Check if the given class has the correct form.
 * /*from   w  w w.j a v  a2  s  . c o m*/
 * <ul>
 * <li>must have exactly one public constructor.</li>
 * <li>must at least have one parameter.</li>
 * <li>all the parameters must be annotated with @Column annotation.</li>
 * </ul>
 * 
 * @param clazz
 * @return
 */
public static boolean hasConstructorInTheCorrectForm(Class<?> clazz) {

    if (clazz.getConstructors().length != 1) {
        return false;
    }

    Constructor<?> con = clazz.getConstructors()[0];

    if (con.getParameterTypes().length == 0) {
        return false;
    }

    Annotation[][] parameterAnnotations = con.getParameterAnnotations();
    for (Annotation[] as : parameterAnnotations) {
        if (!hasColumnAnnotation(as)) {
            return false;
        }
    }

    return true;
}

From source file:com.asual.summer.core.util.ClassUtils.java

public static Object newInstance(String clazz, Object... parameters)
        throws SecurityException, ClassNotFoundException {
    Class<?>[] classParameters = new Class[parameters == null ? 0 : parameters.length];
    for (int i = 0; i < classParameters.length; i++) {
        classParameters[i] = parameters[i].getClass();
    }//from w w w .ja va  2 s.c  o  m
    Object instance = null;
    try {
        instance = Class.forName(clazz).getConstructor(classParameters)
                .newInstance(parameters == null ? new Object[] {} : parameters.length);
    } catch (Exception e) {
        Constructor<?>[] constructors = Class.forName(clazz).getConstructors();
        for (Constructor<?> constructor : constructors) {
            Class<?>[] types = constructor.getParameterTypes();
            if (types.length == parameters.length) {
                Object[] params = new Object[parameters.length];
                for (int i = 0; i < parameters.length; i++) {
                    if (types[i] == boolean.class || types[i] == Boolean.class) {
                        params[i] = Boolean.valueOf(parameters[i].toString());
                    } else if (types[i] == int.class || types[i] == Integer.class) {
                        params[i] = Integer.valueOf(parameters[i].toString());
                    } else {
                        params[i] = types[i].cast(parameters[i]);
                    }
                }
                try {
                    instance = constructor.newInstance(params);
                    break;
                } catch (Exception ex) {
                    continue;
                }
            }
        }
    }
    return instance;
}

From source file:org.apache.drill.common.util.DrillExceptionUtil.java

/**
 * Get throwable from class name and its constructors, the candidate constructor of exception are:
 * 1) ExceptionClass(String message, Throwable t),
 * 2) ExceptionClass(Throwable t, String message),
 * 3) ExceptionClass(String message)./* w w  w . java  2s .  c  om*/
 * if no match constructor found, the base Throwable (Exception or Error) is created as a substitution
 *
 * @param className the exception class name
 * @param message the exception message
 * @param inner the parent cause of the exception
 * @return Throwable
 */
private static Throwable getInstance(String className, String message, Throwable inner)
        throws ReflectiveOperationException {
    Class clazz;
    try {
        clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
        return new Exception(message, inner);
    }
    Constructor<Throwable>[] constructors = clazz.getConstructors();
    Class<?>[] defaultParameterTypes = new Class<?>[] { String.class, Throwable.class };
    Class<?>[] revertParameterTypes = new Class<?>[] { Throwable.class, String.class };
    Class<?>[] singleParameterType = new Class<?>[] { String.class };
    for (Constructor<Throwable> constructor : constructors) {
        if (Arrays.equals(defaultParameterTypes, constructor.getParameterTypes())) {
            return constructor.newInstance(message, inner);
        }
        if (Arrays.equals(revertParameterTypes, constructor.getParameterTypes())) {
            return constructor.newInstance(inner, message);
        }
        if (inner == null) {
            if (Arrays.equals(singleParameterType, constructor.getParameterTypes())) {
                return constructor.newInstance(message);
            }
        }
    }
    return getBaseInstance(clazz, message, inner);
}

From source file:com.swingtech.commons.testing.JavaBeanTester.java

private static Object buildValue(Class<?> clazz) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, SecurityException, InvocationTargetException {
    // If we are using a Mocking framework try that first...
    final Object mockedObject = buildMockValue(clazz);
    if (mockedObject != null) {
        return mockedObject;
    }/*from   w w w .  j av  a 2  s .c  o  m*/

    // Next check for a no-arg constructor
    final Constructor<?>[] ctrs = clazz.getConstructors();
    for (Constructor<?> ctr : ctrs) {
        if (ctr.getParameterTypes().length == 0) {
            // The class has a no-arg constructor, so just call it
            return ctr.newInstance();
        }
    }

    // Specific rules for common classes
    if (clazz == String.class) {
        return "testvalue";

    } else if (clazz.isArray()) {
        return Array.newInstance(clazz.getComponentType(), 1);

    } else if (clazz == boolean.class || clazz == Boolean.class) {
        return true;

    } else if (clazz == int.class || clazz == Integer.class) {
        return 1;

    } else if (clazz == long.class || clazz == Long.class) {
        return 1L;

    } else if (clazz == double.class || clazz == Double.class) {
        return 1.0D;

    } else if (clazz == float.class || clazz == Float.class) {
        return 1.0F;

    } else if (clazz == char.class || clazz == Character.class) {
        return 'Y';

        // Add your own rules here

    } else {
        fail("Unable to build an instance of class " + clazz.getName() + ", please add some code to the "
                + JavaBeanTester.class.getName() + " class to do this.");
        return null; // for the compiler
    }
}

From source file:org.openvpms.web.component.im.view.IMObjectCollectionViewerFactory.java

/**
 * Returns a constructor to construct a new viewer.
 *
 * @param type       the Viewer type/*w  w w  .  jav a 2  s  .c  om*/
 * @param collection the collection property
 * @param object     the parent of the collection
 * @param context    the layout context. May be {@code null}
 * @return a constructor to construct the viewer, or {@code null} if none can be found
 */
private static Constructor getConstructor(Class type, CollectionProperty collection, IMObject object,
        LayoutContext context) {
    Constructor[] ctors = type.getConstructors();

    for (Constructor ctor : ctors) {
        // check parameters
        Class<?>[] ctorTypes = ctor.getParameterTypes();
        if (ctorTypes.length == 3) {
            Class<?> ctorCollection = ctorTypes[0];
            Class<?> ctorObj = ctorTypes[1];
            Class<?> ctorCtx = ctorTypes[2];

            if (ctorCollection.isAssignableFrom(collection.getClass())
                    && ctorObj.isAssignableFrom(object.getClass())
                    && ((context != null && ctorCtx.isAssignableFrom(context.getClass()))
                            || (context == null && LayoutContext.class.isAssignableFrom(ctorCtx)))) {
                return ctor;
            }
        }
    }
    return null;
}

From source file:org.spongepowered.common.util.ReflectionUtil.java

@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(final Class<T> objectClass, Object... args) {
    final Constructor<?>[] ctors = objectClass.getConstructors();
    if (args == null) {
        args = new Object[] { null };
    }//from   w  w w  .ja  va  2  s.  c o m
    // labeled loops
    dance: for (final Constructor<?> ctor : ctors) {
        final Class<?>[] paramTypes = ctor.getParameterTypes();
        if (paramTypes.length != args.length) {
            for (Object object : args) {
                if (object != null) { // hahahah
                    if (object.getClass().isArray()) {
                        final Object[] objects = deconstructArray(args).toArray();
                        return findConstructor(objectClass, objects);
                    }
                }
            }
            continue; // we haven't found the right constructor
        }
        for (int i = 0; i < paramTypes.length; i++) {
            final Class<?> parameter = paramTypes[i];
            if (!isAssignable(args[i] == null ? null : args[i].getClass(), parameter, true)) {
                continue dance; // continue the outer loop since we didn't find the right one
            }
        }
        // We've found the right constructor, now to actually construct it!
        return (Constructor<T>) ctor;
    }
    throw new IllegalArgumentException("Applicable constructor not found for class: "
            + objectClass.getCanonicalName() + " with args: " + Arrays.toString(args));
}