Example usage for java.lang.reflect Method getParameterTypes

List of usage examples for java.lang.reflect Method getParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getParameterTypes.

Prototype

@Override
public Class<?>[] getParameterTypes() 

Source Link

Usage

From source file:hu.bme.mit.sette.tools.spf.SpfGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        // skip container with higher java version than supported
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO error handling
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }/*from   w w  w .j ava2 s . com*/

        for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // create .jpf descriptor
            JPFConfig jpfConfig = new JPFConfig();
            jpfConfig.target = javaClass.getName() + '_' + method.getName();

            String symbMethod = javaClass.getName() + '.' + method.getName() + '('
                    + StringUtils.repeat("sym", "#", parameterTypes.length) + ')';

            jpfConfig.symbolicMethod.add(symbMethod);

            jpfConfig.classpath = "build/";

            for (File libraryFile : getSnippetProject().getFiles().getLibraryFiles()) {
                jpfConfig.classpath += ',' + getSnippetProjectSettings().getLibraryDirectoryPath() + '/'
                        + libraryFile.getName();
            }

            jpfConfig.listener = JPFConfig.SYMBOLIC_LISTENER;
            jpfConfig.symbolicDebug = JPFConfig.ON;

            jpfConfig.searchMultipleErrors = JPFConfig.TRUE;
            jpfConfig.decisionProcedure = JPFConfig.DP_CORAL;

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());

            String[] parameterLiterals = new String[parameterTypes.length];

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                parameterLiterals[i] = SpfGenerator.getParameterLiteral(parameterType);
                i++;
            }

            main.codeLines().add(javaClass.getSimpleName() + '.' + method.getName() + '('
                    + StringUtils.join(parameterLiterals, ", ") + ");");

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathJPF = relativePath + '.' + JPFConfig.JPF_CONFIG_EXTENSION;
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetJPFFile = new File(getRunnerProjectSettings().getGeneratedDirectory(), relativePathJPF);
            FileUtils.forceMkdir(targetJPFFile.getParentFile());
            FileUtils.write(targetJPFFile, jpfConfig.generate().toString());

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

From source file:com.agileapes.couteau.context.spring.event.impl.AbstractMappedEventsTranslationScheme.java

@Override
public void fillIn(Event originalEvent, ApplicationEvent translated) throws EventTranslationException {
    for (Method method : originalEvent.getClass().getMethods()) {
        if (!method.getName().matches("set[A-Z].*") || !Modifier.isPublic(method.getModifiers())
                || !method.getReturnType().equals(void.class) || method.getParameterTypes().length != 1) {
            continue;
        }/*from ww  w  .  jav  a2s.  c  om*/
        final String propertyName = StringUtils.uncapitalize(method.getName().substring(3));
        final Field field = ReflectionUtils.findField(translated.getClass(), propertyName);
        if (field == null || !method.getParameterTypes()[0].isAssignableFrom(field.getType())) {
            continue;
        }
        field.setAccessible(true);
        try {
            method.invoke(originalEvent, field.get(translated));
        } catch (Exception e) {
            throw new EventTranslationException("Failed to set property on original event: " + propertyName, e);
        }
    }
}

From source file:net.nelz.simplesm.aop.CacheBase.java

protected Method getKeyMethod(final Object keyObject) throws NoSuchMethodException {
    final Method storedMethod = methodStore.find(keyObject.getClass());
    if (storedMethod != null) {
        return storedMethod;
    }//from ww  w . j  av  a2  s.  c  o m
    final Method[] methods = keyObject.getClass().getDeclaredMethods();
    Method targetMethod = null;
    for (final Method method : methods) {
        if (method != null && method.getAnnotation(CacheKeyMethod.class) != null) {
            if (method.getParameterTypes().length > 0) {
                throw new InvalidAnnotationException(
                        String.format("Method [%s] must have 0 arguments to be annotated with [%s]",
                                method.toString(), CacheKeyMethod.class.getName()));
            }
            if (!String.class.equals(method.getReturnType())) {
                throw new InvalidAnnotationException(
                        String.format("Method [%s] must return a String to be annotated with [%s]",
                                method.toString(), CacheKeyMethod.class.getName()));
            }
            if (targetMethod != null) {
                throw new InvalidAnnotationException(String.format(
                        "Class [%s] should have only one method annotated with [%s]. See [%s] and [%s]",
                        keyObject.getClass().getName(), CacheKeyMethod.class.getName(), targetMethod.getName(),
                        method.getName()));
            }
            targetMethod = method;
        }
    }

    if (targetMethod == null) {
        targetMethod = keyObject.getClass().getMethod("toString", null);
    }

    methodStore.add(keyObject.getClass(), targetMethod);

    return targetMethod;
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

private Class<?> validateMethodParameters(Class annotation, Method method) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length != 1) {
        throw new IllegalStateException(annotation.getSimpleName() + " method must receive a single parameter");
    }//  ww  w.  j ava  2 s .c o  m
    Class<?> parameter = parameterTypes[0];
    if (annotation == Relationship.class) {
        if (!parameter.isAssignableFrom(JsonApiRelationship.class)) {
            throw new IllegalStateException(
                    annotation.getSimpleName() + " method must receive a " + "JSonApiRelationship parameter");
        }
    } else {
        if (!parameter.isAssignableFrom(String.class)) {
            throw new IllegalStateException(
                    annotation.getSimpleName() + " method must receive a string parameter");
        }
    }
    return parameter;
}

From source file:pl.com.bottega.ecommerce.system.infrastructure.events.impl.EventListenerBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (!(bean instanceof SagaInstance)) {
        for (Method method : bean.getClass().getMethods()) {
            EventListener listenerAnnotation = method.getAnnotation(EventListener.class);

            if (listenerAnnotation == null) {
                continue;
            }//from  w ww .jav  a2 s .  c o  m

            Class<?> eventType = method.getParameterTypes()[0];

            if (listenerAnnotation.asynchronous()) {
                //TODO just a temporary fake impl
                EventHandler handler = new AsynchronousEventHandler(eventType, beanName, method, beanFactory);
                //TODO add to some queue
                eventPublisher.registerEventHandler(handler);
            } else {
                EventHandler handler = new SpringEventHandler(eventType, beanName, method, beanFactory);
                eventPublisher.registerEventHandler(handler);
            }
        }
    }
    return bean;
}

From source file:com.drillmap.crm.repository.extensions.invoker.ReflectionRepositoryInvoker.java

@Override
public Iterable<Object> invokeFindAll(Pageable pageable) {

    if (!exposesFindAll()) {
        return Collections.emptyList();
    }/* w  w w .jav a  2 s  . c  o  m*/

    Method method = methods.getFindAllMethod();
    Class<?>[] types = method.getParameterTypes();

    if (types.length == 0) {
        return invoke(method);
    }

    if (Sort.class.isAssignableFrom(types[0])) {
        return invoke(method, pageable == null ? null : pageable.getSort());
    }

    return invoke(method, pageable);
}

From source file:com.laidians.utils.ClassUtils.java

/**
 * Given a method, which may come from an interface, and a target class used
 * in the current reflective invocation, find the corresponding target method
 * if there is one. E.g. the method may be <code>IFoo.bar()</code> and the
 * target class may be <code>DefaultFoo</code>. In this case, the method may be
 * <code>DefaultFoo.bar()</code>. This enables attributes on that method to be found.
 * <p><b>NOTE:</b> In contrast to {@link org.springframework.aop.support.AopUtils#getMostSpecificMethod},
 * this method does <i>not</i> resolve Java 5 bridge methods automatically.
 * Call {@link org.springframework.core.BridgeMethodResolver#findBridgedMethod}
 * if bridge method resolution is desirable (e.g. for obtaining metadata from
 * the original method definition).//from  ww w. j av a 2s.  com
 * @param method the method to be invoked, which may come from an interface
 * @param targetClass the target class for the current invocation.
 * May be <code>null</code> or may not even implement the method.
 * @return the specific target method, or the original method if the
 * <code>targetClass</code> doesn't implement it or is <code>null</code>
 */
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
    Method specificMethod = null;
    if (method != null && isOverridable(method, targetClass) && targetClass != null
            && !targetClass.equals(method.getDeclaringClass())) {
        specificMethod = ReflectionUtils.findMethod(targetClass, method.getName(), method.getParameterTypes());
    }
    return (specificMethod != null ? specificMethod : method);
}

From source file:com.ebay.jetstream.management.HtmlResourceFormatter.java

@Override
protected final void formatBean(Object bean) throws Exception {
    Class<?> bclass = bean.getClass();
    ManagedResource mr = bclass.getAnnotation(ManagedResource.class);
    String help = mr == null ? null : mr.description();
    formatBean(false, bclass, help);/* ww  w  .ja  v  a 2s  . c o m*/
    boolean section = false;
    for (PropertyDescriptor pd : Introspector.getBeanInfo(bclass).getPropertyDescriptors()) {
        Method getter = pd.getReadMethod();
        if (!XMLSerializationManager.isHidden(getter)) {
            if (!section) {
                section = true;
                formatSection(false, "Properties");
            }
            formatProperty(bean, pd);
        }
    }
    if (section) {
        formatSection(true, "Properties");
    }
    section = false;
    for (Method method : bean.getClass().getMethods()) {
        ManagedOperation mo = method.getAnnotation(ManagedOperation.class);
        if (mo != null && method.getParameterTypes().length == 0) {
            help = mo.description();
            if (!section) {
                section = true;
                formatSection(false, "Operations");
            }
            formatOperation(method);
        }
        if (section) {
            formatSection(true, "Operations");
        }
    }
}

From source file:edu.umn.msi.tropix.common.reflect.ReflectionHelperImpl.java

public Object invoke(final String methodName, final Object targetObject, final Object... arguments) {
    Method targetMethod = null;/* w  w w  . j  a v a2s.c o m*/
    outer: for (final Method method : targetObject.getClass().getMethods()) {
        if (!method.getName().equals(methodName)) {
            continue;
        }
        final Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length != arguments.length) {
            continue;
        }
        for (int i = 0; i < arguments.length; i++) {
            if (arguments[i] != null
                    && !box(parameterTypes[i]).isAssignableFrom(box(arguments[i].getClass()))) {
                continue outer;
            }
        }
        targetMethod = method;
        break;
    }
    if (targetMethod == null) {
        throw new IllegalArgumentException("No such method " + methodName);
    }
    return this.invoke(targetMethod, targetObject, arguments);
}

From source file:com.qmetry.qaf.automation.testng.pro.QAFTestNGListener2.java

@SuppressWarnings("rawtypes")
public void transform(ITestAnnotation testAnnotation, Class clazz, Constructor arg2, Method method) {
    try {/*from   www.j ava  2s . c o m*/
        if ((method.getAnnotation(QAFDataProvider.class) != null) && (null != method.getParameterTypes())
                && (null != method) && (method.getParameterTypes().length > 0)) {
            String dp = getDataProvider(method);
            if (StringUtil.isNotBlank(dp)) {
                testAnnotation.setDataProvider(dp);
                testAnnotation.setDataProviderClass(DataProviderUtil.class);
            }
        }

        if (null != method) {

            String tmtURL = getBundle().getString(method.getName() + ".testspec.url");
            if (StringUtil.isNotBlank(tmtURL)) {
                String desc = String.format("%s<br/><a href=\"%s\">[test-spec]</a>",
                        testAnnotation.getDescription(), tmtURL);
                testAnnotation.setDescription(desc);
            }
            if (getBundle().getBoolean("report.javadoc.link", false)) {
                String linkRelPath = String.format("%s%s.html#%s",
                        getBundle().getString("javadoc.folderpath", "../../../docs/tests/"),
                        method.getDeclaringClass().getCanonicalName().replaceAll("\\.", "/"),
                        ClassUtil.getMethodSignture(method, false));

                String desc = String.format(
                        "%s " + getBundle().getString("report.javadoc.link.format",
                                "<a href=\"%s\" target=\"_blank\">[View-doc]</a>"),
                        testAnnotation.getDescription(), linkRelPath);
                testAnnotation.setDescription(desc);
            }
            testAnnotation
                    .setDescription(getBundle().getSubstitutor().replace(testAnnotation.getDescription()));

            testAnnotation.setRetryAnalyzer(Class
                    .forName(ApplicationProperties.RETRY_ANALYZER.getStringVal(RetryAnalyzer.class.getName())));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}