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:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.MethodMapSicherheitAttributeSource.java

/**
 * Add an attribute for a "gesichert" method. Method names can end or start with "*" for matching multiple
 * methods.//from   www .ja  v a 2s . com
 * @param clazz
 *            target interface or class
 * @param mappedName
 *            mapped method name
 * @param attr
 *            attribute associated with the method
 */
public void addGesichertMethod(Class<?> clazz, String mappedName, String[] attr) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(mappedName, "Mapped name must not be null");
    String name = clazz.getName() + '.' + mappedName;

    Method[] methods = clazz.getDeclaredMethods();
    List<Method> matchingMethods = new ArrayList<Method>();
    for (Method method : methods) {
        if (isMatch(method.getName(), mappedName)) {
            matchingMethods.add(method);
        }
    }
    if (matchingMethods.isEmpty()) {
        throw new IllegalArgumentException(
                "Couldn't find method '" + mappedName + "' on class [" + clazz.getName() + "]");
    }

    // register all matching methods
    for (Method method : matchingMethods) {
        String regMethodName = this.methodNameMap.get(method);
        if (regMethodName == null || (!regMethodName.equals(name) && regMethodName.length() <= name.length())) {
            // No already registered method name, or more specific
            // method name specification now -> (re-)register method.
            if (regMethodName != null) {
                LOG.debug(
                        "Replacing attribute for gesichert method [{}]: current name '{}' is more specific than '{}'",
                        method, name, regMethodName);
            }
            this.methodNameMap.put(method, name);
            addGesichertMethod(method, attr);
        } else {
            LOG.debug(
                    "Keeping attribute for gesichert method [{}]: current name '{}' is not more specific than '{}'",
                    method, name, regMethodName);
        }
    }
}

From source file:com.hortonworks.streamline.streams.service.UDFCatalogResource.java

private Method findMethod(Class<?> clazz, String name) {
    for (Method method : clazz.getDeclaredMethods()) {
        if (method.getName().equals(name) && !method.isBridge()) {
            return method;
        }/*from w  w  w . j  a  va2  s  .  co m*/
    }
    return null;
}

From source file:com.github.jknack.handlebars.helper.DefaultHelperRegistry.java

/**
 * <p>//from  w  w w . j a va 2  s . c  o m
 * Register all the helper methods for the given helper source.
 * </p>
 *
 * @param source The helper source.
 * @param clazz The helper source class.
 */
private void registerDynamicHelper(final Object source, final Class<?> clazz) {
    int size = helpers.size();
    int replaced = 0;
    if (clazz != Object.class) {
        Set<String> overloaded = new HashSet<String>();
        // Keep backing up the inheritance hierarchy.
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            boolean isPublic = Modifier.isPublic(method.getModifiers());
            String helperName = method.getName();
            if (isPublic && CharSequence.class.isAssignableFrom(method.getReturnType())) {
                boolean isStatic = Modifier.isStatic(method.getModifiers());
                if (source != null || isStatic) {
                    if (helpers.containsKey(helperName)) {
                        replaced++;
                    }
                    isTrue(overloaded.add(helperName), "name conflict found: " + helperName);
                    registerHelper(helperName, new MethodHelper(method, source));
                }
            }
        }
    }
    isTrue((size + replaced) != helpers.size(), "No helper method was found in: " + clazz.getName());
}

From source file:com.conversantmedia.mapreduce.tool.annotation.handler.MaraAnnotationUtil.java

/**
 * Convenience method for finding the first annotated method in a given class.
 * /*from   w  w w .j a  v a 2 s  .co  m*/
 * @param clazz            the class to reflect
 * @param annotationClasses   the annotations to look for
 * @return               the methods annotated with the provided list
 */
@SuppressWarnings("unchecked")
public List<Method> findAnnotatedMethods(Class<?> clazz, Class<? extends Annotation>... annotationClasses) {
    List<Method> methods = new ArrayList<>();
    for (Method method : clazz.getDeclaredMethods()) {
        for (Class<? extends Annotation> annotationClass : annotationClasses) {
            if (AnnotationUtils.findAnnotation(method, annotationClass) != null) {
                methods.add(method);
            }
        }
    }
    return methods;
}

From source file:org.slc.sli.dashboard.manager.component.impl.CustomizationAssemblyFactoryImpl.java

private final void findEntityReferencesForType(Map<String, InvokableSet> entityReferenceToManagerMethodMap,
        Class<?> type, Object instance) {
    Manager.EntityMapping entityMapping;
    for (Method m : type.getDeclaredMethods()) {
        entityMapping = m.getAnnotation(Manager.EntityMapping.class);
        if (entityMapping != null) {
            if (entityReferenceToManagerMethodMap.containsKey(entityMapping.value())) {
                throw new DashboardException(
                        "Duplicate entity mapping references found for " + entityMapping.value() + ". Fix!!!");
            }/*from   w  ww.  jav a 2  s  .c o m*/
            if (!Arrays.equals(ENTITY_REFERENCE_METHOD_EXPECTED_SIGNATURE, m.getParameterTypes())) {
                throw new DashboardException("Wrong signature for the method for " + entityMapping.value()
                        + ". Expected is " + Arrays.asList(ENTITY_REFERENCE_METHOD_EXPECTED_SIGNATURE) + "!!!");
            }
            entityReferenceToManagerMethodMap.put(entityMapping.value(), new InvokableSet(instance, m));
        }
    }
}

From source file:bboss.org.apache.velocity.util.introspection.ClassMap.java

private void populateMethodCacheWith(MethodCache methodCache, Class classToReflect) {
    if (debugReflection && log.isDebugEnabled()) {
        log.debug("Reflecting " + classToReflect);
    }//w w  w . j  a  va2s .  com

    try {
        Method[] methods = classToReflect.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            int modifiers = methods[i].getModifiers();
            if (Modifier.isPublic(modifiers)) {
                methodCache.put(methods[i]);
            }
        }
    } catch (SecurityException se) // Everybody feels better with...
    {
        if (log.isDebugEnabled()) {
            log.debug("While accessing methods of " + classToReflect + ": ", se);
        }
    }
}

From source file:com.sinosoft.one.mvc.web.impl.module.ControllerRef.java

private void init() {
    List<MethodRef> actions = new LinkedList<MethodRef>();
    Class<?> clz = controllerClass;
    ///* ww w . j a v a 2s.  c  om*/
    List<Method> pastMethods = new LinkedList<Method>();
    while (true) {
        Method[] declaredMethods = clz.getDeclaredMethods();

        //class?ReqMethodvalue??ReqMethod?methodName
        //sort?,???????0?0+1??,??????
        Arrays.sort(declaredMethods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        //?ReqMethod?ReqMethod.value?
        Map<ReqMethod, Method> checkReqMethod = new HashMap<ReqMethod, Method>();

        for (Method method : declaredMethods) {
            if (quicklyPass(pastMethods, method, controllerClass)) {
                continue;
            }

            Map<ReqMethod, String[]> shotcutMappings = collectsShotcutMappings(method);
            if (shotcutMappings.size() == 0) {
                if (ignoresCommonMethod(method)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("ignores common methods of controller " + controllerClass.getName() + "#"
                                + method.getName());
                    }
                } else {
                    // TODO: ?0.91.0?201007??
                    if ("get".equals(method.getName()) || "index".equals(method.getName())) {
                        // ??get/index@Get?@Get??
                        throw new IllegalArgumentException(
                                "please add @Get to " + controllerClass.getName() + "#" + method.getName());
                    }
                    if ("post".equals(method.getName()) || "delete".equals(method.getName())
                            || "put".equals(method.getName())) {
                        // ??post/delete/put@Get/@Delete/@Put?@Get??
                        throw new IllegalArgumentException(
                                "please add @" + StringUtils.capitalize(method.getName()) + " to "
                                        + controllerClass.getName() + "#" + method.getName());
                    }
                    shotcutMappings = new HashMap<ReqMethod, String[]>();
                    shotcutMappings.put(ReqMethod.GET, new String[] { "/" + method.getName() });
                    shotcutMappings.put(ReqMethod.POST, new String[] { "/" + method.getName() });
                }
            }
            if (shotcutMappings.size() > 0) {
                MethodRef methodRef = new MethodRef();
                for (Map.Entry<ReqMethod, String[]> entry : shotcutMappings.entrySet()) {

                    //?ReqMethod?ReqMethod.value?
                    if (entry.getValue().length == 1 && entry.getValue()[0].equals("")) {
                        if (checkReqMethod.get(entry.getKey()) == null) {
                            checkReqMethod.put(entry.getKey(), method);
                        } else {
                            entry.setValue(new String[] { "/" + method.getName() });
                        }
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("[MethodPath] create:" + entry.getKey() + "="
                                + Arrays.toString(entry.getValue()));
                    }
                    methodRef.addMapping(entry.getKey(), entry.getValue());
                }
                methodRef.setMethod(method);
                actions.add(methodRef);
            }
        }
        for (int i = 0; i < declaredMethods.length; i++) {
            pastMethods.add(declaredMethods[i]);
        }
        clz = clz.getSuperclass();
        if (clz == null || clz.getAnnotation(AsSuperController.class) == null) {
            break;
        }
    }
    this.actions = actions;
}

From source file:de.hybris.platform.webservices.util.objectgraphtransformer.impl.AbstractNodeConfig.java

/**
 * Creates a lookup map containing all properties of passed type.
 * <p/>//from  w w  w  .  j  a  v a  2 s .  c  o m
 * Result maps a property name to a {@link PropertyConfig}.
 * </p>
 * Any property which keeps java bean standard is found and used for {@link PropertyConfig} creation. For finding all
 * properties {@link Introspector} is used which returns general {@link PropertyDescriptor}. But read- and write
 * methods provided by {@link PropertyDescriptor} are only used as "suggestion" here and are getting post-processed
 * to assure following criteria:
 * <p/>
 * - no bridge or synthetic methods are allowed <br/>
 * - co-variant return types are handled correctly <br/>
 * 
 * @param type
 * @return
 */
private Map<String, PropertyConfig> createPropertiesFor(Class<?> type) {
    final Map<String, PropertyConfig> result = new TreeMap<String, PropertyConfig>();
    final Set<String> done = new HashSet<String>();
    while (type != null) {
        // we are only interested in declared methods (no bridge/synthetic ones)
        final Method[] methods = type.getDeclaredMethods();
        for (final Method method : methods) {
            // only public, non-bridged methods are of interest
            if (!method.isBridge() && Modifier.isPublic(method.getModifiers())) {
                // potential bean-getter property?
                if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) {
                    // not processed yet?
                    final String methodName = method.getName();
                    if (!done.contains(methodName)) {
                        done.add(methodName);

                        final Matcher matcher = BEAN_GETTER.matcher(methodName);
                        String propertyName = null;
                        if (matcher.matches()) {
                            propertyName = matcher.group(1);
                        } else {
                            if (method.getReturnType().equals(boolean.class)) {
                                final Matcher matcher2 = BEAN_BOOLEAN_GETTER.matcher(methodName);
                                if (matcher2.matches()) {
                                    propertyName = matcher2.group(1);
                                }
                            }
                        }

                        if (propertyName != null) {
                            propertyName = normalizePropertyName(propertyName);

                            // get or create a PropertyConfig
                            DefaultPropertyConfig pCfg = (DefaultPropertyConfig) result.get(propertyName);
                            if (pCfg == null) {
                                pCfg = new DefaultPropertyConfig(propertyName, null, null);
                                result.put(propertyName, pCfg);
                            }
                            pCfg.setReadMethod(method);
                        }
                    }
                }

                // potential bean-setter property?
                if (method.getParameterTypes().length == 1 && method.getReturnType() == void.class) {
                    // not processed yet?
                    final String methodName = method.getName();
                    if (!done.contains(methodName)) {
                        done.add(methodName);
                        final Matcher setter = BEAN_SETTER.matcher(methodName);
                        if (setter.matches()) {
                            String propertyName = setter.group(1);
                            propertyName = Character.toLowerCase(propertyName.charAt(0))
                                    + propertyName.substring(1);

                            // get or create a PropertyConfig
                            DefaultPropertyConfig pCfg = (DefaultPropertyConfig) result.get(propertyName);
                            if (pCfg == null) {
                                pCfg = new DefaultPropertyConfig(propertyName, null, null);
                                result.put(propertyName, pCfg);
                            }
                            pCfg.setWriteMethod(method);
                        }
                    }
                }
            }

        }
        type = type.getSuperclass();
    }
    return result;
}

From source file:de.tolina.common.validation.AnnotationValidation.java

/**
 * Calls dependent on the type of the given Object:
 * <br> - {@link AnnotationUtils#getAnnotations(Method)} or
 * <br> - {@link AnnotationUtils#getAnnotations(java.lang.reflect.AnnotatedElement)}
 *///from w w  w .j av  a  2  s  .c  om
@Nullable
private Annotation[] getAllAnnotationsFor(@Nonnull final Object annotated) {
    if (annotated instanceof Field) {
        return getAnnotations((Field) annotated);
    }

    if (annotated instanceof Method) {
        final Method annotatedMethod = (Method) annotated;
        final Class<?> declaringClass = annotatedMethod.getDeclaringClass();
        final List<Class<?>> allClasses = new ArrayList<>();
        allClasses.add(declaringClass);
        allClasses.addAll(ClassUtils.getAllSuperclasses(declaringClass));

        final ArrayList<Annotation> allAnnotations = new ArrayList<>();

        for (final Class<?> aClass : allClasses) {
            final ArrayList<Method> allMethods = new ArrayList<>();
            allMethods.addAll(Arrays.asList(aClass.getDeclaredMethods()));

            final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(aClass);
            for (final Class<?> anInterface : interfaces) {
                allMethods.addAll(Arrays.asList(anInterface.getDeclaredMethods()));
            }

            allMethods.stream().filter(method -> isSameMethod(method, annotatedMethod))
                    .forEachOrdered(method -> addIfNotPresent(allAnnotations, getAnnotations(method)));
        }

        return allAnnotations.toArray(new Annotation[] {});
    }

    final Class<?> annotatedClass = (Class<?>) annotated;
    final List<Class<?>> allClasses = new ArrayList<>();
    allClasses.add(annotatedClass);
    allClasses.addAll(ClassUtils.getAllSuperclasses(annotatedClass));

    final ArrayList<Annotation> allAnnotations = new ArrayList<>();

    for (final Class<?> aClass : allClasses) {
        addIfNotPresent(allAnnotations, getAnnotations(aClass));
        final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(aClass);
        for (final Class<?> anInterface : interfaces) {
            addIfNotPresent(allAnnotations, getAnnotations(anInterface));
        }
    }

    return allAnnotations.toArray(new Annotation[] {});
}

From source file:org.apache.camel.util.ObjectHelper.java

/**
 * Returns a list of methods which are annotated with the given annotation
 *
 * @param type the type to reflect on//www  .  j  a v  a  2s .c o m
 * @param annotationType the annotation type
 * @param checkMetaAnnotations check for meta annotations
 * @return a list of the methods found
 */
public static List<Method> findMethodsWithAnnotation(Class<?> type, Class<? extends Annotation> annotationType,
        boolean checkMetaAnnotations) {
    List<Method> answer = new ArrayList<Method>();
    do {
        Method[] methods = type.getDeclaredMethods();
        for (Method method : methods) {
            if (hasAnnotation(method, annotationType, checkMetaAnnotations)) {
                answer.add(method);
            }
        }
        type = type.getSuperclass();
    } while (type != null);
    return answer;
}