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:io.konik.utils.RandomInvoiceGenerator.java

private Object createNewInstance(Class<?> root) throws InstantiationException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    try {//from  ww  w  .j av a 2s . co  m
        if (root.isArray()) {
            Object[] array = (Object[]) Array.newInstance(root.getComponentType(), 1);
            Class<?> componentType = root.getComponentType();
            array[0] = populteData(componentType, componentType.getName());
            return array;
        }
        return root.newInstance();
    } catch (IllegalAccessException e) {
        Constructor<?> biggestConstructor = findBiggestConstructor(root);
        //for each parameter populate data
        Class<?>[] constructorParameters = biggestConstructor.getParameterTypes();
        Object[] constructorParameterObjects = new Object[constructorParameters.length];
        for (int i = 0; i < constructorParameters.length; i++) {
            Class<?> cp = constructorParameters[i];
            constructorParameterObjects[i] = populteData(cp, biggestConstructor.getName());
        }
        return biggestConstructor.newInstance(constructorParameterObjects);
    } catch (InstantiationException e) {
        if (root.equals(CommonTax.class)) {
            //            return ZfDateFactory.create(supportedDateFormatts[random.nextInt(3)]);
        }
        //         throw e;
        e.printStackTrace();
        return null;
    }
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

private Object createObject(Constructor ctor) {
    Object o;/*w  ww.  j a  v  a 2s .  c o  m*/
    int argSize = ctor.getParameterTypes().length;
    Class[] parameterTypes = ctor.getParameterTypes();
    Object[] args = new Object[argSize];

    for (int i = 0; i < argSize; i++) {
        try {
            args[i] = createObjectForType(parameterTypes[i], ctor.getGenericParameterTypes()[i]);
        } catch (Throwable e) {
            e.printStackTrace();
            fail(String.format("Unable to create object %s %d %s %s", ctor, i, parameterTypes[i],
                    ctor.getGenericParameterTypes()[i]));
            return null;
        }

    }
    try {
        o = ctor.newInstance(args);
    } catch (Throwable t) {
        if (!Options.class.equals(ctor.getDeclaringClass())) {
            t.printStackTrace();
            fail(String.format("Unable to create object for %s", ctor));
        }
        return null;
    }
    return o;
}

From source file:org.xmlsh.util.JavaUtils.java

public static Constructor<?> getBeanConstructor(Class<?> targetClass, Class<?> sourceClass)
        throws InvalidArgumentException {
    try {/*from  ww  w . jav  a 2 s  .c  o m*/
        Constructor<?> c = targetClass.getConstructor(sourceClass);
        if (c != null)
            return c;

    } catch (NoSuchMethodException | SecurityException e) {
        mLogger.info("Exception getting constructors for: " + targetClass.getName(), e);
        return null;
    }

    Constructor<?>[] cs = targetClass.getConstructors();

    for (Constructor<?> c : cs) {
        Class<?>[] params = c.getParameterTypes();
        if (params.length == 1) {
            int convert = canConvertClass(sourceClass, params[0]);
            if (convert >= 0)
                return c;
        }
    }
    return null;
}

From source file:com.mewmew.fairy.v1.cli.AnnotatedCLI.java

public AnnotatedCLI(Class... clazz) {
    final List<AnnotatedOption> list = new ArrayList<AnnotatedOption>();
    for (Class aClass : clazz) {
        for (Field field : aClass.getDeclaredFields()) {
            Param param = field.getAnnotation(Param.class);
            if (param != null) {
                list.add(new AnnotatedOption(aClass, field, param));
            }//from   w w  w  .  j  ava  2 s  . c  o  m
            Args arg = field.getAnnotation(Args.class);
            if (arg != null) {
                args.put(aClass, field);
            }
        }
        for (Constructor ctor : aClass.getConstructors()) {
            AnnotatedConstructor actor = new AnnotatedConstructor(aClass, ctor);
            Class[] types = ctor.getParameterTypes();
            Annotation[][] annotations = ctor.getParameterAnnotations();
            for (int i = 0; i < types.length; i++) {
                Class type = types[i];
                Annotation[] ann = annotations[i];
                for (Annotation annotation : ann) {
                    if (annotation instanceof Param) {
                        actor.addParam((Param) annotation, type);
                    }
                }
            }
            if (actor.isValid()) {
                ctors.put(aClass, actor);
            }
        }
    }
    options = new Options();
    mappings = Multimaps.newMultimap(Maps.<Class, Collection<AnnotatedOption>>newHashMap(),
            new Supplier<Collection<AnnotatedOption>>() {
                public Collection<AnnotatedOption> get() {
                    return new ArrayList<AnnotatedOption>();
                }
            });
    for (AnnotatedConstructor constructor : ctors.values()) {
        for (AnnotatedConstructor.AnnotatedParam param : constructor.getParams()) {
            boolean hasArgs = !(param.getType().equals(boolean.class) || param.getType().equals(Boolean.class));
            String option = param.getParam().option();
            while (options.hasOption(option)) {
                option = option + option;
            }
            options.addOption(option, param.getParam().name(), hasArgs, param.getParam().desc());
        }
    }
    for (AnnotatedOption opt : list) {
        boolean hasArgs = !(opt.field.getType().equals(boolean.class)
                || opt.field.getType().equals(Boolean.class));
        while (options.hasOption(opt.getOpt())) {
            opt.setOpt(opt.getOpt() + opt.getOpt());
        }
        options.addOption(opt.getOpt(), opt.getName(), hasArgs, opt.getParam().desc());
        mappings.put(opt.clazz, opt);
    }
}

From source file:org.amanzi.neo.providers.context.ProviderContextImpl.java

@SuppressWarnings("unchecked")
protected <T> T createInstance(final Class<? extends T> clazz,
        final Map<Class<? extends Object>, Object> parametersMap)
        throws InvocationTargetException, IllegalAccessException, InstantiationException, ContextException {
    Constructor<?> correctConstructor = null;
    Object[] arguments = null;/*from   w  w w .  ja va  2  s .co m*/

    for (Constructor<?> constructor : clazz.getConstructors()) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();

        arguments = new Object[parameterTypes.length];

        int i = 0;

        if (parameterTypes.length == parametersMap.size()) {
            boolean isFound = false;
            for (Class<?> argumentType : parameterTypes) {
                for (Entry<Class<? extends Object>, Object> parameterEntry : parametersMap.entrySet()) {
                    Class<?> parameterClass = parameterEntry.getKey();
                    if (argumentType.isAssignableFrom(parameterClass)) {
                        isFound = true;

                        arguments[i++] = parameterEntry.getValue();

                        break;
                    }
                }

                if (!isFound) {
                    break;
                }
            }

            if (isFound) {
                correctConstructor = constructor;
            }
        }
    }

    if (correctConstructor == null) {
        throw new ContextException("Unable to create <" + clazz.getSimpleName()
                + ">. Constructor for Parameters <" + parametersMap.keySet() + "> not found.");
    }

    return (T) correctConstructor.newInstance(arguments);
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

@Test
public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
        InstantiationException, IOException {
    Reflections reflections = new Reflections(this.getClass().getPackage().getName(),
            new SubTypesScanner(false));

    Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
    for (Object clazz : allClasses) {
        String className = ((Class) clazz).getName();
        if (className.contains("com.basistech.rosette.dm")) {
            continue;
        }//from w ww  .ja v a2  s  . co m
        if (className.contains("Adm")) {
            continue; // these are too hard.
        }
        if (className.endsWith(".ModelTest")) {
            continue;
        }
        if (className.endsWith(".NonNullTest")) {
            continue;
        }
        if (className.endsWith("Mixin")) {
            continue;
        }

        if (className.endsWith("Builder")) {
            continue;
        }
        if (className.contains(".batch.")) {
            // there are polymorphism issues in here for this test strategy.
            continue;
        }

        Class c = Class.forName(className);
        if (Modifier.isAbstract(c.getModifiers())) {
            continue;
        }
        Constructor[] ctors = c.getDeclaredConstructors();
        if (ctors.length == 0) {
            continue;
        }
        Constructor ctor = ctors[0];
        if (ctor.getParameterTypes().length == 0) {
            continue; // don't want empty constructor
        }
        Object o1;
        if (Modifier.isPublic(ctor.getModifiers())) {

            boolean oldInputStreams = inputStreams;
            try {
                if (className.endsWith("ConstantsResponse")) {
                    inputStreams = false; // special case due to Object in there.
                }
                o1 = createObject(ctor);
            } finally {
                inputStreams = oldInputStreams;
            }

            // serialize
            // for a request, we might need a view
            ObjectWriter writer = mapper.writerWithView(Object.class);
            if (o1 instanceof DocumentRequest) {
                DocumentRequest r = (DocumentRequest) o1;
                if (r.getRawContent() instanceof String) {
                    writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class);
                }
            }
            String json = writer.writeValueAsString(o1);
            // deserialize
            Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz);
            // verify
            assertEquals(o1, o2);
        }
    }
}

From source file:org.omnaest.utils.reflection.ReflectionUtils.java

/**
 * Resolves a matching constructor for the given type and the given parameter types
 * /*from   ww  w .  j a  va 2  s . co m*/
 * @param type
 * @param parameterTypes
 * @return
 */
public static <C> Constructor<C> resolveConstructorFor(Class<C> type, Class<?>... parameterTypes) {
    //
    Constructor<C> retval = null;

    //
    if (type != null) {
        //
        @SuppressWarnings("unchecked")
        Constructor<C>[] constructors = (Constructor<C>[]) type.getConstructors();
        if (constructors != null) {
            for (Constructor<C> constructor : constructors) {
                Class<?>[] parameterTypesOfContstructor = constructor.getParameterTypes();
                boolean areConstructorTypesAssignableFromParameterTypes = areAssignableFrom(
                        parameterTypesOfContstructor, parameterTypes);
                if (areConstructorTypesAssignableFromParameterTypes) {
                    retval = constructor;
                    break;
                }
            }
        }
    }

    //
    return retval;
}

From source file:eu.sathra.io.IO.java

private SerializeInfo getSerializeInfo(Class<?> clazz) {
    if (!mCache.containsKey(clazz)) {
        SerializeInfo myInfo = new SerializeInfo();

        // Find annotated constructor
        for (Constructor<?> myConstructor : clazz.getConstructors()) {
            Deserialize myDeserialize = myConstructor.getAnnotation(Deserialize.class);

            myInfo.types = myConstructor.getParameterTypes();

            if (myDeserialize != null) {
                myInfo.constructor = myConstructor;
                Defaults myDefaults = myConstructor.getAnnotation(Defaults.class);

                myInfo.params = myDeserialize.value();

                if (myDefaults != null)
                    myInfo.defaults = myDefaults.value();

                mCache.put(clazz, myInfo);
                break;
            }/*from  ww  w .  j  a v  a 2  s.com*/

        }
    }

    return mCache.get(clazz);
}

From source file:com.netflix.simianarmy.basic.BasicSimianArmyContext.java

/**
 * Generic factory to create monkey collateral types.
 *
 * @param <T>/*from   ww w .j av  a 2s.c o m*/
 *            the generic type to create
 * @param implClass
 *            the actual concrete type to instantiate.
 * @return an object of the requested type
 */
private <T> T factory(Class<T> implClass) {
    try {
        // then find corresponding ctor
        for (Constructor<?> ctor : implClass.getDeclaredConstructors()) {
            Class<?>[] paramTypes = ctor.getParameterTypes();
            if (paramTypes.length != 1) {
                continue;
            }
            if (paramTypes[0].getName().endsWith("Configuration")) {
                @SuppressWarnings("unchecked")
                T impl = (T) ctor.newInstance(config);
                return impl;
            }
        }
        // Last ditch; try no-arg.
        return implClass.newInstance();
    } catch (Exception e) {
        LOGGER.error("context config error, cannot make an instance of " + implClass.getName(), e);
    }
    return null;
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

private Constructor<?> findCustomConstructor(Class<?> typeClass) {
    Class<?> superClass = typeClass.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)) {
        Constructor<?> customSuperConstructor = findCustomConstructor(typeClass.getSuperclass());
        if (customSuperConstructor != null) {
            return customSuperConstructor;
        }/* w  w w .  j  a va2  s  .c  om*/
    }
    Constructor<?>[] constructors = typeClass.getConstructors();
    if (constructors.length == 0
            || (constructors.length == 1 && constructors[0].getParameterTypes().length == 0)) {
        return null;
    } else {
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterTypes().length > 0) {
                return constructor;
            }
        }
        //this should never happen
        throw new RuntimeException(String.format(
                "Expected a constructor taking at least one argument in %s but no such constructors were found",
                typeClass.getName()));
    }
}