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:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java

public static Method getMethod(Class<?> cl, String method, Class<?>[] args) {
    for (Method m : cl.getMethods()) {
        if ((m.getName().equals(method)) && (ClassListEqual(args, m.getParameterTypes()))) {
            return m;
        }//from  w  ww . j a va2  s.c o  m
    }
    return null;
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep) {
    try {//from w ww . j av a2  s  .co  m
        if (object == null)
            throw new InvalidParameterException("'object' must not be null.");

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

        MCElement e = clazz.getAnnotation(MCElement.class);
        if (e == null)
            throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

        BeanWrapperImpl dst = new BeanWrapperImpl(clazz);
        BeanWrapperImpl src = new BeanWrapperImpl(object);

        for (Method m : clazz.getMethods()) {
            if (!m.getName().startsWith("set"))
                continue;
            String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
            MCAttribute a = m.getAnnotation(MCAttribute.class);
            if (a != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCChildElement c = m.getAnnotation(MCChildElement.class);
            if (c != null) {
                if (deep) {
                    dst.setPropertyValue(propertyName, cloneInternal(src.getPropertyValue(propertyName), deep));
                } else {
                    dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
                }
            }
            MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
            if (o != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCTextContent t = m.getAnnotation(MCTextContent.class);
            if (t != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
        }

        return (T) dst.getRootInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.zhangyue.zeus.util.BeanUtils.java

/**
 * map??BeanBean??mapkey??mapkey?OMIT_REG?
 * //from ww w  . j  ava 2  s.com
 * @param <E>
 * @param cla
 * @param map
 * @return
 */
@SuppressWarnings({ "rawtypes" })
public static <E> E toBean(Class<E> cla, Map<String, Object> map) {

    // 
    E obj = null;
    try {
        obj = cla.newInstance();
        if (obj == null) {
            throw new Exception();
        }
    } catch (Exception e) {
        LOG.error(",:" + cla);
        return null;
    }

    // ?mapkey
    Map<String, Object> newmap = new HashMap<String, Object>();
    for (Map.Entry<String, Object> en : map.entrySet()) {
        newmap.put("set" + en.getKey().trim().replaceAll(OMIT_REG, "").toLowerCase(), en.getValue());
    }
    // 
    Method[] ms = cla.getMethods();
    for (Method method : ms) {
        String mname = method.getName().toLowerCase();
        if (mname.startsWith("set")) {

            Class[] clas = method.getParameterTypes();
            Object v = newmap.get(mname);

            if (v != null && clas.length == 1) {
                try {
                    method.invoke(obj, v);
                } catch (Exception e) {
                    LOG.error("," + cla + "." + method.getName()
                            + ".?" + clas[0] + ";:" + v.getClass());
                }
            }
        }
    }

    return obj;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static Method findGetter(Class<?> clazz, String propName) {
    Set<String> expectedNames = new HashSet<>(
            Arrays.asList("get" + propName.substring(0, 1).toUpperCase(Locale.ROOT) + propName.substring(1),
                    "is" + propName.substring(0, 1).toUpperCase(Locale.ROOT) + propName.substring(1) //bool props
            ));//from  w  w w.j a va 2s.c o  m
    for (Method method : clazz.getMethods()) {
        String methodName = method.getName();
        if (!expectedNames.contains(methodName)) {
            continue;
        }
        if (method.getParameterCount() != 0) {
            continue; //getters take no arguments
        }
        Type returnType = method.getGenericReturnType();
        if (returnType.equals(void.class)) {
            continue; //getters return something
        }
        if (methodName.startsWith("is")
                && !(returnType.equals(Boolean.class) || returnType.equals(boolean.class))) {
            continue; //isSomething() only valid for booleans
        }
        return method;
    }
    return null;
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

/**
 * Finds non-standard setters {@link PropertyUtils#getPropertyDescriptors} does not find.
 * The non-standard setters include:/*from www.j  a v a  2  s. c  om*/
 * <ul>
 * <li> Setters that return something instead of {@code void}</li>
 * <li> Setters that take a wrapper argument (e.g. Boolean) when the field is of primitive type (e.g. boolean) - or the other way around.
 * </ul>
 *
 * @param clazz     The class to find non-standard setters from
 * @param fieldName The field to find a non-standard setter for
 * @return The non-standard setter or {@code null}
 */
public static Method getNonStandardSetter(Class<?> clazz, String fieldName) {
    Field field;

    try {
        field = getFieldFromBean(clazz, fieldName);
    } catch (MappingException me) {
        return null;
    }

    String methodName = "set" + StringUtils.capitalize(fieldName);

    for (Method method : clazz.getMethods()) {
        if (isNonVoidSetter(method, methodName) || isAutoboxingSetter(method, methodName, field)) {
            return method;
        }
    }

    return null;
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied
 * name and parameter types. Searches all superclasses up to
 * <code>Object</code>./*ww w . jav a2 s.c o  m*/
 * <p>
 * Returns <code>null</code> if no {@link Method} can be found.
 * 
 * @param clazz the class to introspect
 * @param name the name of the method
 * @param parameterTypes the parameter types of the method (may be
 *            <code>null</code> to indicate any signature)
 * @return the Method object, or <code>null</code> if none found
 */
public static Method findMethod(final Class<?> clazz, final String name, final Class<?>[] parameterTypes) {
    Validate.notNull(clazz, "Class must not be null");
    Validate.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        final Method[] methods = searchType.isInterface() ? searchType.getMethods()
                : searchType.getDeclaredMethods();
        for (final Method method : methods) {
            if (name.equals(method.getName())
                    && (parameterTypes == null || Arrays.equals(parameterTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:org.agiso.core.lang.util.ClassUtils.java

/**
 * Wyszukuje dla wskazanej klasy publiczn metod o okrelonej sygnaturze. Jeli
 * metoda nie zostanie naleziona zwraca {@code null}.
 * <p>W przypadku gdy nie jest okrelona tablica parametrw wywoania, zwraca metod
 * tylko gdy wynik wyszukiwania jest unikatowy, tj. istnieje tylko jedna publiczna
 * metoda o wskazanej nazwie./*from w  w  w  . java  2 s. c  om*/
 * 
 * <p>Based on:
 * org.springframework.util.ClassUtils.getMethodIfAvailable(Class<?>, String, Class<?>...)
 * 
 * @param clazz Klasa do sprawdzenia
 * @param methodName Nazwa wyszukiwanej metody
 * @param paramTypes Tablica typw parametrw wywoania metody
 *     (moe by {@code null} w celu wyszukania dowolnej metody o wskazanej nazwie)
 * @return Znaleziona metoda lub @{code null} gdy nie istnieje lub nie jest unikatowa
 * @see Class#getMethod
 */
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    if (clazz == null) {
        throw new NullPointerException("Klasa musi by okrelona");
    }
    if (methodName == null) {
        throw new NullPointerException("Nazwa metody musi by okrelona");
    }

    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied name
 * and parameter types. Searches all superclasses up to {@code Object}.
 * <p>Returns {@code null} if no {@link Method} can be found.
 * @param clazz the class to introspect//from   w  w  w  .ja  va2 s.c o m
 * @param name the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the Method object, or {@code null} if none found
 */
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 || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:org.agiso.core.lang.util.ClassUtils.java

/**
 * Wyszukuje dla wskazanej klasy publiczn metod o okrelonej sygnaturze. Jeli
 * metoda nie zostanie naleziona wyrzuca wyjtek {@code IllegalStateException}.
 * <p>W przypadku gdy nie jest okrelona tablica parametrw wywoania, zwraca metod
 * tylko gdy wynik wyszukiwania jest unikatowy, tj. istnieje tylko jedna publiczna
 * metoda o wskazanej nazwie./*from   w w w  .ja v a  2 s.  com*/
 * 
 * <p>Based on:
 * org.springframework.util.ClassUtils.getMethod(Class<?>, String, Class<?>...)
 * 
 * @param clazz Klasa do sprawdzenia
 * @param methodName Nazwa wyszukiwanej metody
 * @param paramTypes Tablica typw parametrw wywoania metody
 *     (moe by {@code null} w celu wyszukania dowolnej metody o wskazanej nazwie)
 * @return Znaleziona metoda (niegdy {@code null})
 * @throws IllegalStateException jeli nie znaleziono metody lub nie jest unikatowa
 * @see Class#getMethod
 */
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    if (clazz == null) {
        throw new NullPointerException("Klasa musi by okrelona");
    }
    if (methodName == null) {
        throw new NullPointerException("Nazwa metody musi by okrelona");
    }

    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            throw new IllegalStateException("Expected method not found: " + ex);
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        } else if (candidates.isEmpty()) {
            throw new IllegalStateException("Expected method not found: " + clazz + "." + methodName);
        } else {
            throw new IllegalStateException("No unique method found: " + clazz + "." + methodName);
        }
    }
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * @param writer/* ww w .j a  v  a  2  s . c  o  m*/
 * @param type
 * @param expression
 * @author lizj
 */
public static void write(final java.io.Writer writer, final Class<?> type, final String expression) {
    String name = null;
    String text = null;

    Method[] methods = type.getMethods();

    try {
        for (int i = 0; i < methods.length; i++) {
            name = methods[i].getName();

            if (name.startsWith("get") && methods[i].getParameterTypes().length < 1) {
                name = name.substring(3);
                name = java.beans.Introspector.decapitalize(name);

                text = expression;
                text = StringUtil.replace(text, "${name}", name);
                text = StringUtil.replace(text, "${endl}", "\r\n");

                writer.write(text);
            }
        }

        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}