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:org.opendaylight.controller.cluster.datastore.DatastoreContextIntrospector.java

private Object constructorValueRecursively(Class<?> toType, Object fromValue) throws Exception {
    LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})", toType.getSimpleName(), fromValue,
            fromValue.getClass().getSimpleName());

    Constructor<?> ctor = constructors.get(toType);

    LOG.trace("Found {}", ctor);

    if (ctor == null) {
        throw new IllegalArgumentException(String.format("Constructor not found for type %s", toType));
    }/*from   w  w w .j a va 2s. co m*/

    Object value = fromValue;

    // Since the original input type is a String, once we find a constructor that takes a String
    // argument, we're done recursing.
    if (!ctor.getParameterTypes()[0].equals(String.class)) {
        value = constructorValueRecursively(ctor.getParameterTypes()[0], fromValue);
    }

    return ctor.newInstance(value);
}

From source file:de.fuberlin.wiwiss.r2r.Repository.java

private FunctionManager loadFunctionManager(Source source) {
    String fm = Config.getProperty("r2r.FunctionManager", "de.fuberlin.wiwiss.r2r.BasicFunctionManager");
    String error = null;/*from  w  w w  . j av a2  s.com*/
    Exception exception;
    try {
        Class<?> fmclass = Class.forName(fm);
        boolean constructorWithSource = false;
        Constructor<?> c = null;
        for (Constructor<?> constructor : fmclass.getConstructors()) {
            Class<?>[] pTypes = constructor.getParameterTypes();
            if (c == null && pTypes.length == 0)
                c = constructor;
            if (pTypes.length == 1 && pTypes[0] == Source.class) {
                c = constructor;
                constructorWithSource = true;
            }
        }

        if (constructorWithSource)
            return (FunctionManager) c.newInstance(source);
        else
            return (FunctionManager) c.newInstance();
    } catch (InstantiationException e) {
        exception = e;
    } catch (IllegalAccessException e) {
        exception = e;
    } catch (ClassNotFoundException e) {
        exception = e;
    } catch (IllegalArgumentException e) {
        exception = e;
    } catch (InvocationTargetException e) {
        exception = e;
    }
    error = "Could not load Function Manager: " + fm + ". Cause: " + exception;
    if (log.isDebugEnabled())
        log.debug(error);
    if (Config.rethrowActivated())
        throw new R2RException(error, exception);

    return null;
}

From source file:org.evosuite.setup.TestClusterGenerator.java

/**
 * If we try to get deterministic tests, we must not include these
 * constructors// www.j  a  va  2 s. co m
 * 
 * @param c
 * @return
 */
private static boolean isForbiddenNonDeterministicCall(Constructor<?> c) {
    if (!Properties.REPLACE_CALLS)
        return false;

    // Date default constructor uses current time
    if (c.getDeclaringClass().equals(Date.class)) {
        if (c.getParameterTypes().length == 0)
            return true;
    }

    // Random without seed parameter is...random
    if (c.getDeclaringClass().equals(Random.class)) {
        if (c.getParameterTypes().length == 0)
            return true;
    }

    return false;
}

From source file:org.apache.accumulo.test.ShellServerTest.java

private DistCp newDistCp() {
    try {/*  ww  w .  j  av a 2s .c om*/
        @SuppressWarnings("unchecked")
        Constructor<DistCp>[] constructors = (Constructor<DistCp>[]) DistCp.class.getConstructors();
        for (Constructor<DistCp> constructor : constructors) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            if (parameterTypes.length > 0 && parameterTypes[0].equals(Configuration.class)) {
                if (parameterTypes.length == 1) {
                    return constructor.newInstance(new Configuration());
                } else if (parameterTypes.length == 2) {
                    return constructor.newInstance(new Configuration(), null);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    throw new RuntimeException("Unexpected constructors for DistCp");
}

From source file:com.konakart.server.KKGWTServiceImpl.java

/**
 * Create a new KKAppEng engine from a class of the specified name. We look at the constructors
 * in the specified class to find out if there are any constructors declared that will accept an
 * EngineConfig object. If there are, we use that constructor with the specified EngineConfig
 * object. If not, we use the default constructor.
 * /*from w  w  w .j a v a  2s.  c  o  m*/
 * @param kkEngineName
 *            the name of the class that implements KKAppEng
 * @param engConfig
 *            the engine configuration object
 * @return a newly-instantiated KKAppEng
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 */
private KKAppEng getAppEngByName(String kkEngineName, EngineConfigIf engConfig) throws InstantiationException,
        IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException {
    System.out.println("getAppEngByName(" + kkEngineName + ")");
    Class<?> engineClass = Class.forName(kkEngineName);
    KKAppEng kkAppEng = null;
    Constructor<?>[] constructors = engineClass.getConstructors();
    Constructor<?> engConstructor = null;
    if (constructors != null && constructors.length > 0) {
        for (int i = 0; i < constructors.length; i++) {
            Constructor<?> constructor = constructors[i];
            Class<?>[] parmTypes = constructor.getParameterTypes();
            if (parmTypes != null && parmTypes.length == 1) {
                String parmName = parmTypes[0].getName();
                if (parmName != null && parmName.equals("com.konakart.appif.EngineConfigIf")) {
                    engConstructor = constructor;
                }
            }
        }
    }

    if (engConstructor != null) {
        kkAppEng = (KKAppEng) engConstructor.newInstance(engConfig);
        if (true) {
            if (log.isInfoEnabled()) {
                log.info("Created " + kkEngineName + " using EngineConfigIf constructor for store '"
                        + engConfig.getStoreId() + "'");
            }
        }
    } else {
        kkAppEng = (KKAppEng) engineClass.newInstance();
        if (true) {
            if (log.isInfoEnabled()) {
                log.info("Created " + kkEngineName + " using default constructor for store '"
                        + engConfig.getStoreId() + "'");
            }
        }
    }

    return kkAppEng;
}

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues,
        String parentParamName) {

    if (Map.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Map not supported");
    } else if (Collection.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Collection not supported");
    } else {//w ww .j  av a 2  s  .co  m
        try {
            Constructor[] constructors = clazz.getConstructors();
            Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
            if (constructor == null) {
                constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
            }
            Assert.notNull(constructor, "no default constructor or JsonCreator found");
            int parameterCount = constructor.getParameterTypes().length;
            Object[] args = new Object[parameterCount];
            if (parameterCount > 0) {
                Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();
                Class[] parameters = constructor.getParameterTypes();
                int paramIndex = 0;
                for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                    for (Annotation annotation : annotationsOnParameter) {
                        if (JsonProperty.class == annotation.annotationType()) {
                            JsonProperty jsonProperty = (JsonProperty) annotation;
                            String paramName = jsonProperty.value();
                            List<String> formValue = formValues.get(parentParamName + paramName);
                            Class<?> parameterType = parameters[paramIndex];
                            if (DataType.isSingleValueType(parameterType)) {
                                if (formValue != null) {
                                    if (formValue.size() == 1) {
                                        args[paramIndex++] = DataType.asType(parameterType, formValue.get(0));
                                    } else {
                                        //                                        // TODO create proper collection type
                                        throw new IllegalArgumentException("variable list not supported");
                                        //                                        List<Object> listValue = new ArrayList<Object>();
                                        //                                        for (String item : formValue) {
                                        //                                            listValue.add(DataType.asType(parameterType, formValue.get(0)));
                                        //                                        }
                                        //                                        args[paramIndex++] = listValue;
                                    }
                                } else {
                                    args[paramIndex++] = null;
                                }
                            } else {
                                args[paramIndex++] = recursivelyCreateObject(parameterType, formValues,
                                        parentParamName + paramName + ".");
                            }
                        }
                    }
                }
                Assert.isTrue(args.length == paramIndex,
                        "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty");
            }
            Object ret = constructor.newInstance(args);
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                String name = propertyDescriptor.getName();
                List<String> strings = formValues.get(name);
                if (writeMethod != null && strings != null && strings.size() == 1) {
                    writeMethod.invoke(ret,
                            DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor
                }
            }
            return ret;
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e);
        }
    }
}

From source file:org.openehr.build.RMObjectBuilder.java

private Map<String, Class> attributeType(Class rmClass) {

    Map<String, Class> map = new HashMap<String, Class>();
    Constructor constructor = fullConstructor(rmClass);
    if (constructor == null) {
        throw new IllegalArgumentException("no annotated constructor of " + rmClass + ">");
    }//from ww w.  j a va2 s. c  o  m
    Annotation[][] annotations = constructor.getParameterAnnotations();
    Class[] types = constructor.getParameterTypes();

    if (annotations.length != types.length) {
        throw new IllegalArgumentException("less annotations");
    }
    for (int i = 0; i < types.length; i++) {
        if (annotations[i].length == 0) {
            throw new IllegalArgumentException("missing annotations of attribute " + i);
        }
        Attribute attribute = (Attribute) annotations[i][0];
        map.put(attribute.name(), types[i]);
    }
    return map;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @return the string presentation {@link Constructor} that uses short class names.
 *//* w ww.  j a  v a2 s .  com*/
public static String getShortConstructorString(Constructor<?> constructor) {
    if (constructor == null) {
        return "<null-constructor>";
    }
    StringBuilder buffer = new StringBuilder();
    buffer.append(getShortName(constructor.getDeclaringClass()));
    buffer.append('(');
    // append parameters
    {
        Class<?>[] parameters = constructor.getParameterTypes();
        for (int i = 0; i < parameters.length; i++) {
            Class<?> parameterType = parameters[i];
            if (i != 0) {
                buffer.append(',');
            }
            buffer.append(getShortName(parameterType));
        }
    }
    // close
    buffer.append(')');
    return buffer.toString();
}

From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java

private void testTests(final File dir) throws Exception {
    for (final File file : dir.listFiles()) {
        if (file.isDirectory()) {
            if (!".svn".equals(file.getName())) {
                testTests(file);/*from  w  w  w.j  a va  2 s.com*/
            }
        } else {
            if (file.getName().endsWith(".java")) {
                final int index = new File("src/test/java").getAbsolutePath().length();
                String name = file.getAbsolutePath();
                name = name.substring(index + 1, name.length() - 5);
                name = name.replace(File.separatorChar, '.');
                final Class<?> clazz;
                try {
                    clazz = Class.forName(name);
                } catch (final Exception e) {
                    continue;
                }
                name = file.getName();
                if (name.endsWith("Test.java") || name.endsWith("TestCase.java")) {
                    for (final Constructor<?> ctor : clazz.getConstructors()) {
                        if (ctor.getParameterTypes().length == 0) {
                            for (final Method method : clazz.getDeclaredMethods()) {
                                if (Modifier.isPublic(method.getModifiers())
                                        && method.getAnnotation(Before.class) == null
                                        && method.getAnnotation(BeforeClass.class) == null
                                        && method.getAnnotation(After.class) == null
                                        && method.getAnnotation(AfterClass.class) == null
                                        && method.getAnnotation(Test.class) == null
                                        && method.getReturnType() == Void.TYPE
                                        && method.getParameterTypes().length == 0) {
                                    fail("Method '" + method.getName() + "' in " + name
                                            + " does not declare @Test annotation");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.jboss.spring.aop.JBossAopProxy.java

/**
 * Create the target.// w  w  w.  j  av a 2  s  .  c  o  m
 *
 * @param cache the cache
 * @param params the parameters
 * @return target instance
 * @throws Throwable for any error
 */
private Object createTarget(ContainerCache cache, AOPProxyFactoryParameters params) throws Throwable {
    Advisor advisor = cache.getAdvisor();
    if (advisor != null) {
        org.jboss.aop.ConstructorInfo aopinfo = findAopConstructorInfo(advisor);

        Interceptor[] interceptors = (aopinfo != null) ? aopinfo.getInterceptors() : null;

        if (interceptors != null) {
            ConstructorInvocation inv = new ConstructorInvocation(aopinfo, aopinfo.getInterceptors());
            inv.setArguments(getArguments());
            return inv.invokeNext();
        }

        if (constructorInfo.getParameterTypes().length > 0) {
            Constructor<?> constructor = null;
            if (aopinfo == null) {
                //Fall back to using the class;
                Class<?> clazz = advisor.getClazz();
                Constructor<?>[] ctors = clazz.getConstructors();
                for (Constructor<?> ctor : ctors) {
                    if (matchConstructor(ctor)) {
                        constructor = ctor;
                        break;
                    }
                }
            } else {
                constructor = aopinfo.getConstructor();
            }
            params.setCtor(constructor.getParameterTypes(), getArguments());
        }
    }

    return constructorInfo.newInstance(getArguments());
}