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.jrimum.utilix.text.Field.java

/**
 * L campos texto (String) ou numricos que pode ser obtidos a partir de uma String,
 * usando, por exemplo, o construtor ou o mtodo <code>valueOf</code>.
 * //  ww w. ja  va  2s. c  o  m
 * @param valueAsString
 */
@SuppressWarnings("unchecked")
private void readStringOrNumericField(String valueAsString) {

    Class<?> c = value.getClass();

    for (Constructor<?> cons : c.getConstructors()) {

        if (cons.getParameterTypes().length == 1) {
            if (cons.getParameterTypes()[0].equals(String.class)) {
                try {

                    value = (G) cons.newInstance(valueAsString);

                } catch (IllegalArgumentException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                } catch (InstantiationException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                } catch (IllegalAccessException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                } catch (InvocationTargetException e) {
                    getGenericReadError(e, valueAsString).printStackTrace();
                }
            }
        }
    }
}

From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java

public FunctionImplementationRegistry(DrillConfig config, ScanResult classpathScan) {
    Stopwatch w = Stopwatch.createStarted();

    logger.debug("Generating function registry.");
    localFunctionRegistry = new LocalFunctionRegistry(classpathScan);

    Set<Class<? extends PluggableFunctionRegistry>> registryClasses = classpathScan
            .getImplementations(PluggableFunctionRegistry.class);

    for (Class<? extends PluggableFunctionRegistry> clazz : registryClasses) {
        for (Constructor<?> c : clazz.getConstructors()) {
            Class<?>[] params = c.getParameterTypes();
            if (params.length != 1 || params[0] != DrillConfig.class) {
                logger.warn(/*w  w  w  .j av  a 2 s.  c  om*/
                        "Skipping PluggableFunctionRegistry constructor {} for class {} since it doesn't implement a "
                                + "[constructor(DrillConfig)]",
                        c, clazz);
                continue;
            }

            try {
                PluggableFunctionRegistry registry = (PluggableFunctionRegistry) c.newInstance(config);
                pluggableFuncRegistries.add(registry);
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                logger.warn("Unable to instantiate PluggableFunctionRegistry class '{}'. Skipping it.", clazz,
                        e);
            }

            break;
        }
    }
    logger.info("Function registry loaded.  {} functions loaded in {} ms.", localFunctionRegistry.size(),
            w.elapsed(TimeUnit.MILLISECONDS));
    this.remoteFunctionRegistry = new RemoteFunctionRegistry(new UnregistrationListener());
    this.localUdfDir = getLocalUdfDir(config);
}

From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java

private P createClass(BaseUiPolicyRule rule) throws ClassNotFoundException, InvocationTargetException,
        NoSuchMethodException, InstantiationException, IllegalAccessException {
    P domainPolicy = null;/* w  w  w  . j  av  a  2s.  c  o  m*/
    String classType = rule.getObjectClassType();
    Class<P> domainPolicyClass = (Class<P>) Class.forName(classType);

    Constructor constructor = null;
    Object[] paramValues = null;
    boolean hasConstructor = false;
    for (Constructor con : domainPolicyClass.getConstructors()) {
        hasConstructor = true;
        int parameterSize = con.getParameterTypes().length;
        paramValues = new Object[parameterSize];
        for (int p = 0; p < parameterSize; p++) {
            Annotation[] annotations = con.getParameterAnnotations()[p];
            Object paramValue = null;
            for (Annotation a : annotations) {
                if (a instanceof PolicyPropertyRef) {
                    // this is the one we want
                    if (constructor == null) {
                        constructor = con;
                    }
                    //find the value associated to this property
                    paramValue = getPropertyValue(rule, domainPolicyClass, (PolicyPropertyRef) a);

                }
            }
            paramValues[p] = paramValue;
        }
        if (constructor != null) {
            //exit once we find a constructor with @PropertyRef
            break;
        }

    }

    if (constructor != null) {
        //call that constructor
        try {
            domainPolicy = ConstructorUtils.invokeConstructor(domainPolicyClass, paramValues);
        } catch (NoSuchMethodException e) {
            domainPolicy = domainPolicyClass.newInstance();
        }
    } else {
        //if the class has no public constructor then attempt to call the static instance method
        if (!hasConstructor) {
            //if the class has a static "instance" method on it then call that
            try {
                domainPolicy = (P) MethodUtils.invokeStaticMethod(domainPolicyClass, "instance", null);
            } catch (NoSuchMethodException | SecurityException | InvocationTargetException e) {
                domainPolicy = domainPolicyClass.newInstance();
            }
        } else {
            //attempt to create a new instance
            domainPolicy = domainPolicyClass.newInstance();
        }

    }

    return domainPolicy;

}

From source file:org.apache.cactus.internal.server.AbstractWebTestCaller.java

/**
 * @param theClassName the name of the test class
 * @param theWrappedClassName the name of the wrapped test class. Can be
 *        null if there is none/*ww w .  java2  s .c  om*/
 * @param theTestCaseName the name of the current test case
 * @return an instance of the test class to call
 * @exception ServletException if the test case instance for the current
 *            test fails to be instanciated (for example if some
 *            information is missing from the HTTP request)
 */
protected TestCase getTestClassInstance(String theClassName, String theWrappedClassName, String theTestCaseName)
        throws ServletException {
    // Get the class to call and build an instance of it.
    Class testClass = getTestClassClass(theClassName);
    TestCase testInstance = null;
    Constructor constructor;

    try {
        if (theWrappedClassName == null) {
            constructor = getTestClassConstructor(testClass);

            if (constructor.getParameterTypes().length == 0) {
                testInstance = (TestCase) constructor.newInstance(new Object[0]);
                ((TestCase) testInstance).setName(theTestCaseName);
            } else {
                testInstance = (TestCase) constructor.newInstance(new Object[] { theTestCaseName });
            }
        } else {
            Class wrappedTestClass = getTestClassClass(theWrappedClassName);
            Constructor wrappedConstructor = getTestClassConstructor(wrappedTestClass);

            TestCase wrappedTestInstance;
            if (wrappedConstructor.getParameterTypes().length == 0) {
                wrappedTestInstance = (TestCase) wrappedConstructor.newInstance(new Object[0]);
                wrappedTestInstance.setName(theTestCaseName);
            } else {
                wrappedTestInstance = (TestCase) wrappedConstructor
                        .newInstance(new Object[] { theTestCaseName });
            }

            constructor = testClass.getConstructor(new Class[] { String.class, Test.class });

            testInstance = (TestCase) constructor
                    .newInstance(new Object[] { theTestCaseName, wrappedTestInstance });
        }
    } catch (Exception e) {
        String message = "Error instantiating class [" + theClassName + "([" + theTestCaseName + "], ["
                + theWrappedClassName + "])]";

        LOGGER.error(message, e);
        throw new ServletException(message, e);
    }

    return testInstance;
}

From source file:org.unitils.core.context.Context.java

@SuppressWarnings("unchecked")
protected <T> T createInstanceOfType(Class<T> type, String... classifiers) {
    Class<?> implementationType = getImplementationType(type, classifiers);
    Constructor<?> constructor = getConstructor(implementationType);

    Object[] arguments;/*from  w w  w .ja  v  a2  s . c  om*/
    Class<?>[] parameterTypes;
    if (constructor == null) {
        arguments = new Object[0];
        parameterTypes = new Class[0];

    } else {
        parameterTypes = constructor.getParameterTypes();
        Type[] genericParameterTypes = constructor.getGenericParameterTypes();
        Annotation[][] argumentAnnotations = constructor.getParameterAnnotations();

        arguments = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            arguments[i] = getArgumentInstance(parameterTypes[i], genericParameterTypes[i],
                    argumentAnnotations[i]);
        }
    }
    Object instance = ReflectionUtils.createInstanceOfType(implementationType, true, parameterTypes, arguments);
    if (instance instanceof Factory) {
        instance = ((Factory) instance).create();
    }
    if (!type.isAssignableFrom(instance.getClass())) {
        throw new UnitilsException(
                "Implementation type " + instance.getClass().getName() + " is not of type " + type.getName());
    }
    return (T) instance;
}

From source file:com.mirth.connect.client.ui.LoadedExtensions.java

public void initialize() {
    // Remove all existing extensions from the maps in case they are being
    // initialized again
    clearExtensionMaps();/* w  w w  .  ja  v a2 s  .  co m*/

    // Order all the plugins by their weight before loading any of them.
    Map<String, String> pluginNameMap = new HashMap<String, String>();
    NavigableMap<Integer, List<String>> weightedPlugins = new TreeMap<Integer, List<String>>();
    for (PluginMetaData metaData : PlatformUI.MIRTH_FRAME.getPluginMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (metaData.getClientClasses() != null) {
                    for (PluginClass pluginClass : metaData.getClientClasses()) {
                        String clazzName = pluginClass.getName();
                        int weight = pluginClass.getWeight();
                        pluginNameMap.put(clazzName, metaData.getName());

                        List<String> classList = weightedPlugins.get(weight);
                        if (classList == null) {
                            classList = new ArrayList<String>();
                            weightedPlugins.put(weight, classList);
                        }

                        classList.add(clazzName);
                    }
                }

                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e);
        }
    }

    // Load connector code template plugins before anything else
    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load code template plugin: " + metaData.getTemplateClassName());
        }
    }

    // Signal the reference list factory that code template plugins have been loaded
    ReferenceListFactory.getInstance().loadPluginReferences();

    // Load the plugins in order of their weight
    for (List<String> classList : weightedPlugins.descendingMap().values()) {
        for (String clazzName : classList) {
            try {
                String pluginName = pluginNameMap.get(clazzName);
                Class<?> clazz = Class.forName(clazzName);
                Constructor<?>[] constructors = clazz.getDeclaredConstructors();

                for (int i = 0; i < constructors.length; i++) {
                    Class<?> parameters[];
                    parameters = constructors[i].getParameterTypes();
                    // load plugin if the number of parameters
                    // in the constructor is 1.
                    if (parameters.length == 1) {
                        ClientPlugin clientPlugin = (ClientPlugin) constructors[i]
                                .newInstance(new Object[] { pluginName });
                        addPluginPoints(clientPlugin);
                        i = constructors.length;
                    }
                }
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                        "Could not load plugin class: " + clazzName);
            }
        }
    }

    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {

                String connectorName = metaData.getName();
                ConnectorSettingsPanel connectorSettingsPanel = (ConnectorSettingsPanel) Class
                        .forName(metaData.getClientClassName()).newInstance();

                if (metaData.getType() == ConnectorMetaData.Type.SOURCE) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    sourceConnectors.put(connectorName, connectorSettingsPanel);
                } else if (metaData.getType() == ConnectorMetaData.Type.DESTINATION) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    destinationConnectors.put(connectorName, connectorSettingsPanel);
                } else {
                    // type must be SOURCE or DESTINATION
                    throw new Exception();
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load connector class: " + metaData.getClientClassName());
        }
    }

    // Signal the reference list factory that all other plugins have been loaded
    ReferenceListFactory.getInstance().loadReferencesAfterPlugins();
}

From source file:org.grouplens.grapht.reflect.internal.ClassInstantiator.java

@Override
public Object instantiate() throws ConstructionException {
    // find constructor and build up necessary constructor arguments

    Constructor<?> ctor = getConstructor();
    LogContext globalLogContext = LogContext.create();
    Object instance = null;//from  ww  w. ja v a  2 s . c  om
    Method[] methods;

    try {
        // create the instance that we are injecting
        try {
            globalLogContext.put("org.grouplens.grapht.class", ctor.getClass().toString());
            Object[] ctorArgs = new Object[ctor.getParameterTypes().length];
            for (Desire d : desires) {
                LogContext ipContext = LogContext.create();
                if (d.getInjectionPoint() instanceof ConstructorParameterInjectionPoint) {
                    // this desire is a constructor argument so create it now
                    Instantiator provider = providers.get(d);
                    ConstructorParameterInjectionPoint cd = (ConstructorParameterInjectionPoint) d
                            .getInjectionPoint();
                    logger.trace("Injection point satisfactions in progress {}", cd);
                    try {
                        ipContext.put("org.grouplens.grapht.injectionPoint", cd.toString());
                    } finally {
                        ipContext.finish();
                    }
                    ctorArgs[cd.getParameterIndex()] = checkNull(cd, provider.instantiate());
                }
            }
            logger.trace("Invoking constructor {} with arguments {}", ctor, ctorArgs);
            ctor.setAccessible(true);
            instance = ctor.newInstance(ctorArgs);
        } catch (InvocationTargetException e) {
            throw new ConstructionException(ctor, "Constructor " + ctor + " failed", e);
        } catch (InstantiationException e) {
            throw new ConstructionException(ctor, "Could not instantiate " + type, e);
        } catch (IllegalAccessException e) {
            throw new ConstructionException(ctor, "Access violation on " + ctor, e);
        }

        // satisfy dependencies in the order of the list, which was
        // prepared to comply with JSR 330
        Map<Method, InjectionArgs> settersAndArguments = new HashMap<Method, InjectionArgs>();
        for (Desire d : desires) {
            LogContext ipContext = LogContext.create();
            try {
                final InjectionStrategy injectionStrategy = InjectionStrategy
                        .forInjectionPoint(d.getInjectionPoint());
                ipContext.put("org.grouplens.grapht.injectionPoint", d.getInjectionPoint().toString());
                injectionStrategy.inject(d.getInjectionPoint(), instance, providers.get(d),
                        settersAndArguments);
            } finally {
                ipContext.finish();
            }
        }
    } finally {
        globalLogContext.finish();
    }
    if (manager != null) {
        manager.registerComponent(instance);
    }

    methods = MethodUtils.getMethodsWithAnnotation(type, PostConstruct.class);
    for (Method method : methods) {
        method.setAccessible(true);
        try {
            method.invoke(instance);
        } catch (InvocationTargetException e) {
            throw new ConstructionException("Exception throw by " + method, e);
        } catch (IllegalAccessException e) {
            throw new ConstructionException("Access violation invoking " + method, e);
        }
    }

    // the instance has been fully configured
    return instance;
}

From source file:com.agimatec.validation.jsr303.extensions.MethodValidatorMetaBeanFactory.java

private void buildConstructorConstraints(MethodBeanDescriptorImpl beanDesc)
        throws InvocationTargetException, IllegalAccessException {
    beanDesc.setConstructorConstraints(new HashMap());

    for (Constructor cons : beanDesc.getMetaBean().getBeanClass().getDeclaredConstructors()) {
        if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(cons)) {

            ConstructorDescriptorImpl consDesc = new ConstructorDescriptorImpl(beanDesc.getMetaBean(),
                    new Validation[0]);
            beanDesc.putConstructorDescriptor(cons, consDesc);

            Annotation[][] paramsAnnos = cons.getParameterAnnotations();
            Class[] paramTypes = cons.getParameterTypes();
            int idx = 0;
            for (Annotation[] paramAnnos : paramsAnnos) {
                processAnnotations(consDesc, paramAnnos, paramTypes[idx], idx);
                idx++;/*w ww  .j ava2  s. com*/
            }
        }
    }
}

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

/**
 * @return the {@link Constructor} with minimal number of parameters.
 */// ww w. ja  v  a  2  s  .  c  om
public static Constructor<?> getShortestConstructor(Class<?> clazz) {
    Constructor<?> shortest = null;
    int minCount = Integer.MAX_VALUE;
    for (Constructor<?> constructor : clazz.getConstructors()) {
        int thisCount = constructor.getParameterTypes().length;
        if (minCount > thisCount) {
            shortest = constructor;
            minCount = thisCount;
        }
    }
    return shortest;
}

From source file:org.opoo.press.impl.FactoryImpl.java

@Override
public Renderer createRenderer(Site site) {
    //return new RendererImpl(site, getTemplateLoaders());

    String className = (String) site.getTheme().get("renderer");
    if (className != null) {
        Class<Renderer> clazz;
        try {/*from w ww  . j a v  a  2 s  .  co m*/
            clazz = ClassUtils.getClass(site.getClassLoader(), className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }

        Constructor<?>[] constructors = clazz.getConstructors();
        Constructor<?> theConstructor = null;
        for (Constructor<?> constructor : constructors) {
            Class<?>[] types = constructor.getParameterTypes();
            if (types.length == 1 && types[0].equals(Site.class)) {
                theConstructor = constructor;
                break;
            }
        }

        try {
            if (theConstructor != null) {
                return (Renderer) theConstructor.newInstance(site);
            } else {
                Renderer renderer = clazz.newInstance();
                if (renderer instanceof SiteAware) {
                    ((SiteAware) renderer).setSite(site);
                }
                if (renderer instanceof ConfigAware) {
                    ((ConfigAware) renderer).setConfig(site.getConfig());
                }
                return renderer;
            }

        } catch (InstantiationException e) {
            throw new RuntimeException("error instance: " + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("error instance: " + e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("error instance: " + e.getTargetException(), e.getTargetException());
        }
    }

    //default: freemarker
    return new FreeMarkerRenderer(site);
}