Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

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

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}//from   w  w  w .j a  va  2s  . com
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

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//  w ww.  j  a  v  a  2s.  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:com.github.dactiv.common.utils.ReflectionUtils.java

/**
 * ?DeclaredMethod ?.//from w ww.ja v a2 s  .  c  o  m
 * 
 * @param targetClass
 *            Class
 * @param ignoreParent
 *            ??,?Method
 * 
 * @return List
 */
public static List<Method> getAccessibleMethods(final Class targetClass, boolean ignoreParent) {
    Assert.notNull(targetClass, "targetClass?");
    List<Method> methods = new ArrayList<Method>();

    Class<?> superClass = targetClass;
    do {
        Method[] result = superClass.getDeclaredMethods();

        if (!ArrayUtils.isEmpty(result)) {

            for (Method method : result) {
                method.setAccessible(true);
            }

            CollectionUtils.addAll(methods, result);
        }

        superClass = superClass.getSuperclass();
    } while (superClass != Object.class && !ignoreParent);

    return methods;
}

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

/**
 * Perform the given callback operation on all matching methods of the given
 * class and superclasses (or given interface and super-interfaces).
 * <p>The same named method occurring on subclass and superclass will appear
 * twice, unless excluded by the specified {@link MethodFilter}.
 * @param clazz class to start looking at
 * @param mc the callback to invoke for each method
 * @param mf the filter that determines the methods to apply the callback to
 *//*from w  w w .  j av  a  2 s. c o m*/
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf)
        throws IllegalArgumentException {

    // Keep backing up the inheritance hierarchy.
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        if (mf != null && !mf.matches(method)) {
            continue;
        }
        try {
            mc.doWith(method);
        } catch (IllegalAccessException ex) {
            throw new IllegalStateException(
                    "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
        }
    }
    if (clazz.getSuperclass() != null) {
        doWithMethods(clazz.getSuperclass(), mc, mf);
    } else if (clazz.isInterface()) {
        for (Class<?> superIfc : clazz.getInterfaces()) {
            doWithMethods(superIfc, mc, mf);
        }
    }
}

From source file:com.github.drinkjava2.jbeanbox.springsrc.ReflectionUtils.java

/**
 * This variant retrieves {@link Class#getDeclaredMethods()} from a local cache in order to avoid the JVM's
 * SecurityManager check and defensive array copying.
 *///from   w ww . j av a2 s.  co m
private static Method[] getDeclaredMethods(Class<?> clazz) {
    Method[] result = declaredMethodsCache.get(clazz);
    if (result == null) {
        result = clazz.getDeclaredMethods();
        declaredMethodsCache.put(clazz, result);
    }
    return result;
}

From source file:com.helpinput.utils.Utils.java

public static Method findMethod(Class<?> targetClass, String methodName, Class<?>[] agrsClasses) {
    Method[] methods = targetClass.getDeclaredMethods();
    Method theMethod = null;/*from  w w  w.  j a  v  a 2 s  . co m*/

    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            Class<?>[] classes = method.getParameterTypes();

            if (agrsClasses.length == 0 && classes.length == 0) {
                theMethod = method;
                break;
            }

            if (agrsClasses.length == classes.length) {
                for (int i = 0; i < agrsClasses.length; i++) {
                    if (agrsClasses[i] == null) {
                        if (i == agrsClasses.length - 1) {
                            theMethod = method;
                            break;
                        }
                        continue;
                    }
                    if (classes[i].isPrimitive()) {
                        if (!primitiveWrap(classes[i]).isAssignableFrom(agrsClasses[i]))
                            break;
                    } else if (!classes[i].isAssignableFrom(agrsClasses[i]))
                        break;
                    if (i == agrsClasses.length - 1) {
                        theMethod = method;
                        break;
                    }
                }
            }
            if (theMethod != null)
                break;
        }
        if (theMethod != null)
            break;
    }

    if (null != theMethod) {
        return accessible(theMethod);
    } else {
        if (targetClass.getSuperclass() != null) {
            return findMethod(targetClass.getSuperclass(), methodName, agrsClasses);
        }
        return null;
    }
}

From source file:com.helpinput.core.Utils.java

public static Method findMethod(Object target, String methodName, Object... args) {
    Class<?> targetClass = getClass(target);
    Class<?>[] argsClasses = getArgClasses(args);
    Method[] methods = targetClass.getDeclaredMethods();
    return (Method) findMember(methods, targetClass, methodName, argsClasses);
}

From source file:cop.raml.mocks.MockUtils.java

private static TypeElementMock createClassElement(@NotNull Class<?> cls) throws ClassNotFoundException {
    TypeElementMock element = new TypeElementMock(cls.getName(), ElementKind.CLASS);
    element.setType(new TypeMirrorMock(element, TypeMirrorMock.getTypeKind(cls)));

    if (cls.getName().startsWith("cop.") || cls.getName().startsWith("spring.")) {
        VariableElementMock var;

        for (Field field : cls.getDeclaredFields())
            if ((var = createVariable(field.getName(), field.getType(),
                    Modifier.isStatic(field.getModifiers()))) != null)
                element.addEnclosedElement(setAnnotations(var, field));

        ExecutableElementMock exe;//from   w ww . ja  v  a2 s.  c  o m

        for (Method method : cls.getDeclaredMethods())
            if ((exe = createExecutable(method)) != null)
                element.addEnclosedElement(setAnnotations(exe, method));
    }

    return setAnnotations(element, cls);
}

From source file:com.qingstor.sdk.utils.QSJSONUtil.java

private static boolean initParameter(JSONObject o, Field[] declaredField, Class objClass, Object targetObj)
        throws NoSuchMethodException {
    boolean hasParam = false;
    for (Field field : declaredField) {
        String methodField = QSParamInvokeUtil.capitalize(field.getName());
        String getMethodName = field.getType() == Boolean.class ? "is" + methodField : "get" + methodField;
        String setMethodName = "set" + methodField;
        Method[] methods = objClass.getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals(getMethodName)) {
                ParamAnnotation annotation = m.getAnnotation(ParamAnnotation.class);
                if (annotation == null) {
                    continue;
                }//from ww  w .  j  a v a  2 s . co  m
                String dataKey = annotation.paramName();

                if (o.has(dataKey)) {
                    hasParam = true;
                    Object data = toObject(o, dataKey);
                    Method setM = objClass.getDeclaredMethod(setMethodName, field.getType());
                    setParameterToMap(setM, targetObj, field, data);
                }
            }
        }
    }
    return hasParam;
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private static <T extends Annotation> Set<AccessibleObject> getAnnotatedFieldOrMethod(
        Set<AccessibleObject> fieldsOrMethods, Class<T> annotationClass, Class entityClass,
        boolean withInheritance) {
    for (Field field : entityClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(annotationClass)) {
            fieldsOrMethods.add(field);//w ww. j  a v  a  2s .  co  m
        }
    }
    for (Method method : entityClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(annotationClass)) {
            fieldsOrMethods.add(method);
        }
    }
    if (entityClass.getSuperclass() != null && withInheritance) {
        return getAnnotatedFieldOrMethod(fieldsOrMethods, annotationClass, entityClass.getSuperclass(),
                withInheritance);
    }
    return fieldsOrMethods;
}