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:de.pribluda.android.jsonmarshaller.JSONMarshaller.java

/**
 * recursively marshall to JSON//from  w  w  w.  ja  va  2  s . c  o  m
 *
 * @param sink
 * @param object
 */
static void marshallRecursive(JSONObject sink, Object object)
        throws JSONException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    // nothing to marshall
    if (object == null)
        return;
    // primitive object is a field and does not interes us here
    if (object.getClass().isPrimitive())
        return;
    // object not null,  and is not primitive - iterate through getters
    for (Method method : object.getClass().getMethods()) {
        // our getters are parameterless and start with "get"
        if ((method.getName().startsWith(GETTER_PREFIX) && method.getName().length() > BEGIN_INDEX
                || method.getName().startsWith(IS_PREFIX) && method.getName().length() > IS_LENGTH)
                && (method.getModifiers() & Modifier.PUBLIC) != 0 && method.getParameterTypes().length == 0
                && method.getReturnType() != void.class) {
            // is return value primitive?
            Class<?> type = method.getReturnType();
            if (type.isPrimitive() || String.class.equals(type)) {
                // it is, marshall it
                Object val = method.invoke(object);
                if (val != null) {
                    sink.put(propertize(method.getName()), val);
                }
                continue;
            } else if (type.isArray()) {
                Object val = marshallArray(method.invoke(object));
                if (val != null) {
                    sink.put(propertize(method.getName()), val);
                }
                continue;
            } else if (type.isAssignableFrom(Date.class)) {
                Date date = (Date) method.invoke(object);
                if (date != null) {
                    sink.put(propertize(method.getName()), date.getTime());
                }
                continue;
            } else if (type.isAssignableFrom(Boolean.class)) {
                Boolean b = (Boolean) method.invoke(object);
                if (b != null) {
                    sink.put(propertize(method.getName()), b.booleanValue());
                }
                continue;
            } else if (type.isAssignableFrom(Integer.class)) {
                Integer i = (Integer) method.invoke(object);
                if (i != null) {
                    sink.put(propertize(method.getName()), i.intValue());
                }
                continue;
            } else if (type.isAssignableFrom(Long.class)) {
                Long l = (Long) method.invoke(object);
                if (l != null) {
                    sink.put(propertize(method.getName()), l.longValue());
                }
                continue;
            } else {
                // does it have default constructor?
                try {
                    if (method.getReturnType().getConstructor() != null) {
                        Object val = marshall(method.invoke(object));
                        if (val != null) {
                            sink.put(propertize(method.getName()), val);
                        }
                        continue;
                    }
                } catch (NoSuchMethodException ex) {
                    // just ignore it here, it means no such constructor was found
                }
            }
        }
    }
}

From source file:edu.cornell.mannlib.vedit.util.FormUtils.java

public static void beanSet(Object newObj, String field, String value, EditProcessObject epo) {
    SimpleDateFormat standardDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Class cls = (epo != null && epo.getBeanClass() != null) ? epo.getBeanClass() : newObj.getClass();
    Class[] paramList = new Class[1];
    Method setterMethod = getSetterMethod(cls, field, SUPPORTED_TYPE_LIST);
    if (setterMethod == null) {
        log.debug("Could not find method set" + field + " on " + cls.getName());
        return;//from   w w  w .  j  av  a2  s .co  m
    }
    Class argumentType = setterMethod.getParameterTypes()[0];
    Object[] arglist = new Object[1];
    if (int.class.equals(argumentType) || Integer.class.equals(argumentType)) {
        arglist[0] = (int.class.equals(argumentType)) ? -1 : null;
        if (!value.isEmpty()) {
            int parsedInt = Integer.parseInt(value, BASE_10);
            if (parsedInt < 0) {
                throw new FormUtils.NegativeIntegerException();
            } else {
                arglist[0] = parsedInt;
            }
        }
    } else if (Date.class.equals(argumentType)) {
        // this isn't so great ; should probably be in a validator
        if (value != null && value.length() > 0 && value.indexOf(":") < 1) {
            value += " 00:00:00";
        }
        if (value != null && value.length() > 0) {
            try {
                arglist[0] = standardDateFormat.parse(value);
            } catch (ParseException p) {
                try {
                    arglist[0] = minutesOnlyDateFormat.parse(value);
                } catch (ParseException q) {
                    log.error(FormUtils.class.getName() + " could not parse" + value + " to a Date object.");
                    throw new IllegalArgumentException("Please enter a date/time in one of these "
                            + "formats: '2007-07-07', '2007-07-07 07:07' " + "or '2007-07-07 07:07:07'");
                }
            }
        } else {
            arglist[0] = null;
        }
    } else if (boolean.class.equals(argumentType)) {
        arglist[0] = (value.equalsIgnoreCase("true"));
    } else {
        arglist[0] = value;
    }
    try {
        setterMethod.invoke(newObj, arglist);
    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:com.iisigroup.cap.utils.CapBeanUtil.java

public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods());
        for (Method method : methods) {
            if (name.equals(method.getName()) && (paramTypes == null || paramTypes.length == 0
                    || paramTypes[0] == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }/* ww w  . ja v a  2  s  .  com*/
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:cn.webwheel.ActionSetter.java

public static String isSetter(Method method) {
    if (Modifier.isStatic(method.getModifiers()))
        return null;
    String name = method.getName();
    if (!name.startsWith("set"))
        return null;
    if (name.length() < 4)
        return null;
    if (method.getParameterTypes().length != 1)
        return null;
    name = name.substring(3);/*w  w  w  .ja  v a  2  s  .c  o  m*/
    if (name.length() > 1 && name.equals(name.toUpperCase()))
        return name;
    return name.substring(0, 1).toLowerCase() + name.substring(1);
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Looks for all methods and fields annotated with {@code @SpringBean} and attempts
 * to lookup and inject a managed bean into the field/property. If any annotated
 * element cannot be injected an exception is thrown.
 *
 * @param bean the bean into which to inject spring beans
 * @param ctx the Spring application context
 *//* w  ww.j av a2  s . co  m*/
public static void injectBeans(Object bean, ApplicationContext ctx) {
    // First inject any values using annotated methods
    for (Method m : getMethods(bean.getClass())) {
        try {
            SpringBean springBean = m.getAnnotation(SpringBean.class);
            boolean nameSupplied = !"".equals(springBean.value());
            String name = nameSupplied ? springBean.value() : methodToPropertyName(m);
            Class<?> beanType = m.getParameterTypes()[0];
            Object managedBean = findSpringBean(ctx, name, beanType, !nameSupplied);
            m.invoke(bean, managedBean);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Exception while trying to lookup and inject " + "a Spring bean into a bean of type "
                            + bean.getClass().getSimpleName() + " using method " + m.toString(),
                    e);
        }
    }

    // And then inject any properties that are annotated
    for (Field f : getFields(bean.getClass())) {
        try {
            SpringBean springBean = f.getAnnotation(SpringBean.class);
            boolean nameSupplied = !"".equals(springBean.value());
            String name = nameSupplied ? springBean.value() : f.getName();
            Object managedBean = findSpringBean(ctx, name, f.getType(), !nameSupplied);
            f.set(bean, managedBean);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Exception while trying to lookup and inject " + "a Spring bean into a bean of type "
                            + bean.getClass().getSimpleName() + " using field access on field " + f.toString(),
                    e);
        }
    }
}

From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass,
        boolean required) throws ClassNotFoundException {
    RootBeanDefinition bd = new RootBeanDefinition();
    bd.setBeanClass(beanClass);//w w  w.jav a  2s. c o  m
    // ??lazy init
    bd.setLazyInit(false);

    // id?id,idcontext
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = element.getAttribute("class");
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, bd);
    }
    bd.getPropertyValues().addPropertyValue("id", id);
    if (ProtocolConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.protocolDefineNames.add(id);

    } else if (RegistryConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.registryDefineNames.add(id);

    } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicServiceConfigDefineNames.add(id);

    } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicRefererConfigDefineNames.add(id);

    } else if (ServiceConfigBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(
                    Class.forName(className, true, Thread.currentThread().getContextClassLoader()));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            bd.getPropertyValues().addPropertyValue("ref",
                    new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    }

    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    // ??setbd
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        // setXXX
        if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers())
                || setter.getParameterTypes().length != 1) {
            continue;
        }
        String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-");
        props.add(property);
        if ("id".equals(property)) {
            bd.getPropertyValues().addPropertyValue("id", id);
            continue;
        }
        String value = element.getAttribute(property);
        if ("methods".equals(property)) {
            parseMethods(id, element.getChildNodes(), bd, parserContext);
        }
        if (StringUtils.isBlank(value)) {
            continue;
        }
        value = value.trim();
        if (value.length() == 0) {
            continue;
        }
        Object reference;
        if ("ref".equals(property)) {
            if (parserContext.getRegistry().containsBeanDefinition(value)) {
                BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                if (!refBean.isSingleton()) {
                    throw new IllegalStateException(
                            "The exported service ref " + value + " must be singleton! Please set the " + value
                                    + " bean scope to singleton, eg: <bean id=\"" + value
                                    + "\" scope=\"singleton\" ...>");
                }
            }
            reference = new RuntimeBeanReference(value);
        } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) {
            if (!value.contains(",")) {
                reference = new RuntimeBeanReference(value);
            } else {
                parseMultiRef("protocols", value, bd, parserContext);
                reference = null;
            }
        } else if ("registry".equals(property)) {
            parseMultiRef("registries", value, bd, parserContext);
            reference = null;
        } else if ("basicService".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("basicReferer".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("extConfig".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else {
            reference = new TypedStringValue(value);
        }

        if (reference != null) {
            bd.getPropertyValues().addPropertyValue(property, reference);
        }
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        // protocolparameters?
        NamedNodeMap attributes = element.getAttributes();
        int len = attributes.getLength();
        for (int i = 0; i < len; i++) {
            Node node = attributes.item(i);
            String name = node.getLocalName();
            if (!props.contains(name)) {
                if (parameters == null) {
                    parameters = new ManagedMap();
                }
                String value = node.getNodeValue();
                parameters.put(name, new TypedStringValue(value, String.class));
            }
        }
        bd.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return bd;
}

From source file:Mopex.java

/**
 * Returns a String that is formatted as a Java method declaration having
 * the same header as the specified method but with the code parameter
 * substituted for the method body.//from   w  ww. j ava2s.c o m
 * 
 * @return String
 * @param m
 *            java.lang.Method
 * @param code
 *            String
 */
//start extract createReplacementMethod
public static String createReplacementMethod(Method m, String code) {
    Class[] pta = m.getParameterTypes();
    String fpl = formalParametersToString(pta);
    Class[] eTypes = m.getExceptionTypes();
    String result = m.getName() + "(" + fpl + ")\n";
    if (eTypes.length != 0)
        result += "    throws " + classArrayToString(eTypes) + "\n";
    result += "{\n" + code + "}\n";
    return result;
}

From source file:org.zht.framework.util.ZBeanUtil.java

private static void copy(Object source, Object target, Boolean ignorNull, Class<?> editable,
        String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }//from   w  w w . j  av  a 2s  . c om
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (ignorNull != null && ignorNull) {
                            if (value != null && (!"[]".equals(value.toString()))) {// ?
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                        } else {
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }

                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:com.astamuse.asta4d.data.InjectUtil.java

private final static List<TargetInfo> createMethodTarget(Method method)
        throws InstantiationException, IllegalAccessException {
    Class<?>[] types = method.getParameterTypes();
    List<TargetInfo> targetList = new ArrayList<>();
    if (types.length == 0) {
        return targetList;
    }/*from   ww  w  .  j av a 2  s  .c o m*/
    Annotation[][] annotations = method.getParameterAnnotations();
    String[] parameterNames = paranamer.lookupParameterNames(method);
    TargetInfo target;
    ContextData cd;
    ContextDataSet cdSet;
    for (int i = 0; i < types.length; i++) {
        target = new TargetInfo();
        target.type = types[i];
        target.isContextDataHolder = ContextDataHolder.class.isAssignableFrom(target.type);

        cd = ConvertableAnnotationRetriever.retrieveAnnotation(ContextData.class, annotations[i]);
        cdSet = ConvertableAnnotationRetriever.retrieveAnnotation(ContextDataSet.class,
                target.type.getAnnotations());
        target.name = cd == null ? "" : cd.name();
        target.scope = cd == null ? "" : cd.scope();
        target.typeUnMatch = cd == null ? TypeUnMacthPolicy.EXCEPTION : cd.typeUnMatch();
        if (StringUtils.isEmpty(target.name)) {
            target.name = parameterNames[i];
        }

        if (cdSet == null) {
            target.contextDataSetFactory = null;
        } else {
            target.contextDataSetFactory = cdSet.factory().newInstance();
            target.isContextDataSetSingletonInContext = cdSet.singletonInContext();
        }

        target.fixForPrimitiveType();
        targetList.add(target);
    }
    return targetList;
}

From source file:com.mani.cucumber.ReflectionUtils.java

/**
 * Finds a method of the given name that will accept a parameter of the
 * given type. If more than one method matches, returns the first such
 * method found.//from   w ww  . j a v  a  2  s.  c o m
 *
 * @param target the object to reflect on
 * @param name the name of the method to search for
 * @param parameterType the type of the parameter to be passed
 * @return the matching method
 * @throws IllegalStateException if no matching method is found
 */
public static Method findMethod(Object target, String name, Class<?> parameterType) {

    for (Method method : target.getClass().getMethods()) {
        if (!method.getName().equals(name)) {
            continue;
        }

        Class<?>[] parameters = method.getParameterTypes();
        if (parameters.length != 1) {
            continue;
        }

        if (parameters[0].isAssignableFrom(parameterType)) {
            return method;
        }
    }

    throw new IllegalStateException(
            "No method '" + name + "(" + parameterType + ") on type " + target.getClass());
}