Example usage for java.lang Class getMethods

List of usage examples for java.lang Class getMethods

Introduction

In this page you can find the example usage for java.lang Class getMethods.

Prototype

@CallerSensitive
public Method[] getMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Usage

From source file:es.logongas.ix3.util.ReflectionUtil.java

static public Method getMethod(Class clazz, String methodName) {
    Method[] methods = clazz.getMethods();

    return findUniqueMethodByName(methods, methodName);
}

From source file:com.relicum.ipsum.Reflection.ReflectionUtil.java

/**
 * Gets a {@link Method} in a given {@link Class} object with the specified
 * arguments./*ww w. j av a  2s  .co m*/
 *
 * @param clazz Class object
 * @param name  Method name
 * @param args  Arguments
 * @return The method, or null if none exists
 */
public static final Method getMethod(Class<?> clazz, String name, Class<?>... args) {
    Validate.notNull(clazz, "clazz cannot be null!");
    Validate.notNull(name, "name cannot be null!");
    if (args == null)
        args = new Class<?>[0];

    for (Method method : clazz.getMethods()) {
        if (method.getName().equals(name) && Arrays.equals(args, method.getParameterTypes()))
            return method;
    }

    return null;
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

private static Method findSetterMethod(Class<?> clazz, String name) {
    // Build the method name.
    name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        Class<?> params[] = method.getParameterTypes();
        if (method.getName().equals(name) && params.length == 1) {
            return method;
        }//from  w  ww.j av a  2  s.c om
    }
    return null;
}

From source file:com.espertech.esper.event.bean.PropertyHelper.java

/**
 * Adds to the given list of property descriptors the mapped properties, ie.
 * properties that have a getter method taking a single String value as a parameter.
 * @param clazz to introspect/*from  w w w .  j  av  a  2 s  . c o  m*/
 * @param result is the list to add to
 */
protected static void addMappedProperties(Class clazz, List<InternalEventPropDescriptor> result) {
    Set<String> uniquePropertyNames = new HashSet<String>();
    Method[] methods = clazz.getMethods();

    for (int i = 0; i < methods.length; i++) {
        String methodName = methods[i].getName();
        if (!methodName.startsWith("get")) {
            continue;
        }

        String inferredName = methodName.substring(3, methodName.length());
        if (inferredName.length() == 0) {
            continue;
        }

        Class<?> parameterTypes[] = methods[i].getParameterTypes();
        if (parameterTypes.length != 1) {
            continue;
        }

        if (parameterTypes[0] != String.class) {
            continue;
        }

        String newInferredName = null;
        // Leave uppercase inferred names such as URL
        if (inferredName.length() >= 2) {
            if ((Character.isUpperCase(inferredName.charAt(0)))
                    && (Character.isUpperCase(inferredName.charAt(1)))) {
                newInferredName = inferredName;
            }
        }
        // camelCase the inferred name
        if (newInferredName == null) {
            newInferredName = Character.toString(Character.toLowerCase(inferredName.charAt(0)));
            if (inferredName.length() > 1) {
                newInferredName += inferredName.substring(1, inferredName.length());
            }
        }
        inferredName = newInferredName;

        // if the property inferred name already exists, don't supply it
        if (uniquePropertyNames.contains(inferredName)) {
            continue;
        }

        result.add(new InternalEventPropDescriptor(inferredName, methods[i], EventPropertyType.MAPPED));
        uniquePropertyNames.add(inferredName);
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.ActiveXObject.java

/**
 * Gets the first method found of the class with the given name
 * and the correct annotation//ww  w  .j a  v a  2 s  .  co  m
 * @param clazz the class to search on
 * @param name the name of the searched method
 * @param annotationClass the class of the annotation required
 * @return {@code null} if not found
 */
static Method getMethod(final Class<? extends SimpleScriptable> clazz, final String name,
        final Class<? extends Annotation> annotationClass) {
    if (name == null) {
        return null;
    }

    Method foundMethod = null;
    int foundByNameOnlyCount = 0;
    for (final Method method : clazz.getMethods()) {
        if (method.getName().equals(name)) {
            if (null != method.getAnnotation(annotationClass)) {
                return method;
            }
            foundByNameOnlyCount++;
            foundMethod = method;
        }
    }
    if (foundByNameOnlyCount > 1) {
        throw new IllegalArgumentException(
                "Found " + foundByNameOnlyCount + " methods for name '" + name + "' in class '" + clazz + "'.");
    }
    return foundMethod;
}

From source file:cn.mypandora.util.MyExcelUtil.java

/**
 * Excel?sheet/*w  ww .j a  v  a2 s.co m*/
 *
 * @param sheet      sheet
 * @param objList    ??
 * @param objClass   ???
 * @param fieldNames ?objClassfield??
 */
private static void createBody(Sheet sheet, List<?> objList, Class<?> objClass, String fieldNames) {
    String[] targetMethod = fieldNames.split(",");
    Method[] ms = objClass.getMethods();
    Pattern pattern = Pattern.compile("^get.*");

    // objList?sheet
    for (int objIndex = 0; objIndex < objList.size(); objIndex++) {
        Object obj = objList.get(objIndex);
        Row row = sheet.createRow(objIndex + 1);
        // strBody?sheet
        for (int strIndex = 0; strIndex < targetMethod.length; strIndex++) {
            String targetMethodName = targetMethod[strIndex];
            // msstrBody
            for (int i = 0; i < ms.length; i++) {
                Method srcMethod = ms[i];
                if (pattern.matcher(srcMethod.getName()).matches()) {
                    int len = targetMethodName.indexOf(".") < 0 ? targetMethodName.length()
                            : targetMethodName.indexOf(".");
                    if (srcMethod.getName()
                            .equals(("get"
                                    + String.valueOf(targetMethodName.substring(0, len).charAt(0)).toUpperCase()
                                    + targetMethodName.substring(1, len)))) {
                        Cell cell = row.createCell(strIndex);
                        cell.setCellType(CellType.STRING);
                        try {
                            // 
                            if (targetMethodName.contains(".")) {
                                cell.setCellValue(referenceInvoke(targetMethodName, obj));
                                // 
                            } else {
                                cell.setCellValue((srcMethod.invoke(obj)).toString());
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

}

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

/**
 * Populates form objects with bean values
 *///from   w w  w  .ja  v a2 s.  com
public static void populateFormFromBean(Object bean, String action, EditProcessObject epo, FormObject foo,
        Map<String, String> BadValuesHash) {
    Class beanClass = (epo != null && epo.getBeanClass() != null) ? epo.getBeanClass() : bean.getClass();

    Method[] meths = beanClass.getMethods();

    for (int i = 0; i < meths.length; i++) {

        if (meths[i].getName().indexOf("set") == 0) {

            // we have a setter method
            Method currMeth = meths[i];
            Class[] currMethParamTypes = currMeth.getParameterTypes();
            Class currMethType = currMethParamTypes[0];

            if (SUPPORTED_TYPE_LIST.contains(currMethType)) {
                //we only want people directly to type in ints, strings, and dates
                //of course, most of the ints are probably foreign keys anyway...

                String elementName = currMeth.getName().substring(3, currMeth.getName().length());

                //see if there's something in the bean using
                //the related getter method

                Class[] paramClass = new Class[1];
                paramClass[0] = currMethType;
                try {
                    Method getter = beanClass.getMethod("get" + elementName, (Class[]) null);
                    Object existingData = null;
                    try {
                        existingData = getter.invoke(bean, (Object[]) null);
                    } catch (Exception e) {
                        log.error("Exception invoking getter method");
                    }
                    String value = "";
                    if (existingData != null) {
                        if (existingData instanceof String) {
                            value += existingData;
                        } else if (!(existingData instanceof Integer && (Integer) existingData < 0)) {
                            value += existingData.toString();
                        }
                    }
                    String badValue = (String) BadValuesHash.get(elementName);
                    if (badValue != null) {
                        value = badValue;
                    }
                    foo.getValues().put(elementName, value);
                } catch (NoSuchMethodException e) {
                    //ignore it
                }
            }
        }
    }
}

From source file:com.bluecloud.ioc.classloader.ClassHandler.java

/**
 * <h3>Class</h3>//from   w  w w  .  j a  v  a  2 s  .  c om
 * 
 * @param obj
 *            
 * @param methodName
 *            ??
 * @param args
 *            ?
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public static void invokeMethod(Object obj, String methodName, Object args)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Class<? extends Object> clazz = obj.getClass();
    try {
        if (args != null) {
            clazz.getMethod(methodName, args.getClass()).invoke(obj, args);
        }
    } catch (SecurityException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchMethodException e) {
        for (Method method : clazz.getMethods()) {
            if (method.getName().equals(methodName) && method.getParameterTypes().length == 1) {
                method.invoke(obj, args);
            }
        }
    }
}

From source file:ClassReader.java

protected static Map<String, Method> findAttributeReaders(Class c) {
    Map<String, Method> map = new HashMap<String, Method>();
    Method[] methods = c.getMethods();

    for (int i = 0; i < methods.length; i++) {
        String name = methods[i].getName();
        if (name.startsWith("read") && methods[i].getReturnType() == void.class) {
            map.put(name.substring(4), methods[i]);
        }//from w w w .  j  a  v a  2 s.co  m
    }

    return map;
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * To trim object String field/*from   ww  w .ja va2  s  . c om*/
 * 
 * @param all
 *            default is false. true means toTrim all String field, false toTrim the fields have
 *            net.kamhon.ieagle.vo.core.annotation.ToTrim.
 * 
 * @param objects
 */
public static void toTrimProperties(boolean all, Object... objects) {
    for (Object object : objects) {
        if (object == null) {
            continue;
        }

        // getter for String field only
        Map<String, Method> getterMap = new HashMap<String, Method>();
        // setter for String field only
        Map<String, Method> setterMap = new HashMap<String, Method>();

        Class<?> clazz = object.getClass();

        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                    && method.getReturnType().equals(String.class)) {

                // if method name is getXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                getterMap.put(fieldName, method);
            } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0] == String.class
                    && method.getReturnType().equals(void.class)) {
                // log.debug("setter = " + method.getName());

                // if method name is setXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                setterMap.put(fieldName, method);
            }
        }

        // if the key exists in both getter & setter
        for (String key : getterMap.keySet()) {
            if (setterMap.containsKey(key)) {
                try {
                    Method getterMethod = getterMap.get(key);
                    Method setterMethod = setterMap.get(key);

                    // if not all, check on Field
                    if (!all) {
                        Field field = null;

                        Class<?> tmpClazz = clazz;
                        // looping up to superclass to get decleared field
                        do {
                            try {
                                field = tmpClazz.getDeclaredField(key);
                            } catch (Exception ex) {
                                // do nothing
                            }

                            if (field != null) {
                                break;
                            }

                            tmpClazz = tmpClazz.getSuperclass();
                        } while (tmpClazz != null);

                        ToTrim toTrim = field.getAnnotation(ToTrim.class);
                        if (toTrim == null || toTrim.trim() == false) {
                            continue;
                        }
                    }

                    String value = (String) getterMethod.invoke(object, new Object[] {});

                    if (StringUtils.isNotBlank(value))
                        setterMethod.invoke(object, value.trim());

                } catch (Exception ex) {
                    // log.error("Getter Setter for " + key + " has error ", ex);
                }
            }
        }
    }
}