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.github.gekoh.yagen.ddl.TableConfig.java

private void processTypeAnnotations(Class type, boolean selectiveRendering) {
    do {//from   ww w. j a v  a2 s  . co m
        processAnnotations(type.getDeclaredFields(), selectiveRendering);
        processAnnotations(type.getDeclaredMethods(), selectiveRendering);
    } while ((type = getEntitySuperclass(type)) != null);
}

From source file:org.os890.ds.addon.spring.impl.SpringBridgeExtension.java

private List<Annotation> tryToMapToCdiQualifier(String beanName, BeanDefinition beanDefinition,
        AfterBeanDiscovery abd) {/*w ww.  j ava  2 s . c  o  m*/
    List<Annotation> cdiQualifiers = new ArrayList<Annotation>();
    if (beanDefinition instanceof AbstractBeanDefinition) {
        boolean unsupportedQualifierFound = false;
        for (AutowireCandidateQualifier springQualifier : ((AbstractBeanDefinition) beanDefinition)
                .getQualifiers()) {
            Class qualifierClass = ClassUtils.tryToLoadClassForName(springQualifier.getTypeName());

            if (qualifierClass == null) {
                unsupportedQualifierFound = true;
                break;
            }

            if (Annotation.class.isAssignableFrom(qualifierClass)) {
                Map<String, Object> qualifierValues = new HashMap<String, Object>();
                String methodName;
                Object methodValue;
                for (Method annotationMethod : qualifierClass.getDeclaredMethods()) {
                    methodName = annotationMethod.getName();
                    methodValue = springQualifier.getAttribute(methodName);

                    if (methodValue != null) {
                        qualifierValues.put(methodName, methodValue);
                    }

                }

                cdiQualifiers.add(AnnotationInstanceProvider.of(qualifierClass, qualifierValues));
            } else {
                unsupportedQualifierFound = true;
                break;
            }
        }
        if (unsupportedQualifierFound) {
            abd.addDefinitionError(new IllegalStateException(beanName + " can't be added"));
        }
    }
    return cdiQualifiers;
}

From source file:org.apache.syncope.core.logic.LoggerLogic.java

@PreAuthorize("hasRole('" + StandardEntitlement.AUDIT_LIST + "') or hasRole('"
        + StandardEntitlement.NOTIFICATION_LIST + "')")
public List<EventCategoryTO> listAuditEvents() {
    // use set to avoid duplications or null elements
    Set<EventCategoryTO> events = new HashSet<>();

    try {//from  w  ww.ja  v  a  2  s .  c  om
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(
                        SystemPropertyUtils.resolvePlaceholders(this.getClass().getPackage().getName()))
                + "/**/*.class";

        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                final Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());

                if (clazz.isAnnotationPresent(Component.class) && AbstractLogic.class.isAssignableFrom(clazz)) {
                    EventCategoryTO eventCategoryTO = new EventCategoryTO();
                    eventCategoryTO.setCategory(clazz.getSimpleName());
                    for (Method method : clazz.getDeclaredMethods()) {
                        if (Modifier.isPublic(method.getModifiers())) {
                            eventCategoryTO.getEvents().add(method.getName());
                        }
                    }
                    events.add(eventCategoryTO);
                }
            }
        }

        // SYNCOPE-608
        EventCategoryTO authenticationControllerEvents = new EventCategoryTO();
        authenticationControllerEvents.setCategory(AuditElements.AUTHENTICATION_CATEGORY);
        authenticationControllerEvents.getEvents().add(AuditElements.LOGIN_EVENT);
        events.add(authenticationControllerEvents);

        events.add(new EventCategoryTO(EventCategoryType.PROPAGATION));
        events.add(new EventCategoryTO(EventCategoryType.PULL));
        events.add(new EventCategoryTO(EventCategoryType.PUSH));

        for (AnyTypeKind anyTypeKind : AnyTypeKind.values()) {
            for (ExternalResource resource : resourceDAO.findAll()) {
                EventCategoryTO propEventCategoryTO = new EventCategoryTO(EventCategoryType.PROPAGATION);
                EventCategoryTO syncEventCategoryTO = new EventCategoryTO(EventCategoryType.PULL);
                EventCategoryTO pushEventCategoryTO = new EventCategoryTO(EventCategoryType.PUSH);

                propEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                propEventCategoryTO.setSubcategory(resource.getKey());

                syncEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                pushEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                syncEventCategoryTO.setSubcategory(resource.getKey());
                pushEventCategoryTO.setSubcategory(resource.getKey());

                for (ResourceOperation resourceOperation : ResourceOperation.values()) {
                    propEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                    syncEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                    pushEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                }

                for (UnmatchingRule unmatching : UnmatchingRule.values()) {
                    String event = UnmatchingRule.toEventName(unmatching);
                    syncEventCategoryTO.getEvents().add(event);
                    pushEventCategoryTO.getEvents().add(event);
                }

                for (MatchingRule matching : MatchingRule.values()) {
                    String event = MatchingRule.toEventName(matching);
                    syncEventCategoryTO.getEvents().add(event);
                    pushEventCategoryTO.getEvents().add(event);
                }

                events.add(propEventCategoryTO);
                events.add(syncEventCategoryTO);
                events.add(pushEventCategoryTO);
            }
        }

        for (SchedTask task : taskDAO.<SchedTask>findAll(TaskType.SCHEDULED)) {
            EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
            eventCategoryTO.setCategory(Class.forName(task.getJobDelegateClassName()).getSimpleName());
            events.add(eventCategoryTO);
        }

        EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
        eventCategoryTO.setCategory(PullJobDelegate.class.getSimpleName());
        events.add(eventCategoryTO);

        eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
        eventCategoryTO.setCategory(PushJobDelegate.class.getSimpleName());
        events.add(eventCategoryTO);
    } catch (Exception e) {
        LOG.error("Failure retrieving audit/notification events", e);
    }

    return new ArrayList<>(events);
}

From source file:es.osoco.grails.plugins.otp.access.AnnotationMultipleVoterFilterInvocationDefinition.java

private Map<String, Set<String>> findActionRoles(final Class<?> clazz) {
    // since action closures are defined as "def foo = ..." they're
    // fields, but they end up as private
    Map<String, Set<String>> actionRoles = new HashMap<String, Set<String>>();
    for (Field field : clazz.getDeclaredFields()) {
        Annotation annotation = findAnnotation(field.getAnnotations());
        if (annotation != null) {
            actionRoles.put(field.getName(), asSet(getValue(annotation)));
        }/*w  w  w .  j  a v  a  2 s  . c  om*/
    }
    for (Method method : clazz.getDeclaredMethods()) {
        Annotation annotation = findAnnotation(method.getAnnotations());
        if (annotation != null) {
            actionRoles.put(method.getName(), asSet(getValue(annotation)));
        }
    }
    return actionRoles;
}

From source file:org.codehaus.griffon.commons.ClassPropertyFetcher.java

private void init() {
    FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            if (field.isSynthetic())
                return;
            final int modifiers = field.getModifiers();
            if (!Modifier.isPublic(modifiers))
                return;

            final String name = field.getName();
            if (name.indexOf('$') == -1) {
                boolean staticField = Modifier.isStatic(modifiers);
                if (staticField) {
                    staticFetchers.put(name, new FieldReaderFetcher(field, staticField));
                } else {
                    instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
                }/*  w  w w  . jav a2 s .  c o  m*/
            }
        }
    };

    MethodCallback methodCallback = new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            if (method.isSynthetic())
                return;
            if (!Modifier.isPublic(method.getModifiers()))
                return;
            if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
                if (method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.indexOf('$') == -1) {
                        if (name.length() > 3 && name.startsWith("get")
                                && Character.isUpperCase(name.charAt(3))) {
                            name = name.substring(3);
                        } else if (name.length() > 2 && name.startsWith("is")
                                && Character.isUpperCase(name.charAt(2))
                                && (method.getReturnType() == Boolean.class
                                        || method.getReturnType() == boolean.class)) {
                            name = name.substring(2);
                        }
                        PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                        staticFetchers.put(name, fetcher);
                        staticFetchers.put(StringUtils.uncapitalize(name), fetcher);
                    }
                }
            }
        }
    };

    List<Class<?>> allClasses = resolveAllClasses(clazz);
    for (Class<?> c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                fieldCallback.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            try {
                methodCallback.doWith(method);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
            }
        }
    }

    propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor desc : propertyDescriptors) {
        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            }
        }
    }
}

From source file:de.taimos.dvalin.test.jaxrs.TestProxyBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {//from   w  w  w . j a  v  a2  s . com
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(TestProxy.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@TestProxy annotation is not supported on static fields");
                }
                currElements.add(new TestProxyElement(field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(TestProxy.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@TestProxy annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@TestProxy annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new TestProxyElement(method, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:com.heliosphere.demeter.base.runner.AbstractRunner.java

/**
 * Initializes the runner file annotation.
 * <hr>//from  ww  w .j a v a2  s .c  o m
 * @throws RunnerException Thrown in case an error occurred while trying to initialize the runner.
 * @see RunnerFile
 */
@SuppressWarnings("nls")
private final void initializeRunnerFileAnnotation() throws RunnerException {
    for (Annotation annotation : this.getClass().getAnnotations()) {
        Class<? extends Annotation> type = annotation.annotationType();
        if (type == RunnerFile.class) {
            for (Method method : type.getDeclaredMethods()) {
                Object value = null;

                try {
                    value = method.invoke(annotation, (Object[]) null);
                    if (method.getName().equals("configurationFile")) {
                        this.configuration = new XmlConfigurationFile((String) value);
                    } else {
                        if (method.getName().equals("executionFile")) {
                            if (!((String) value).equals("UNKNOWN")) {
                                this.execution = new XmlExecutionFile((String) value);
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RunnerException(String.format("Unable to initialize runner: %1s due to: %2s",
                            this.getClass().getName(), e.getMessage()), e);
                }
            }
        }
    }
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private <T> Method findPropertyGetterUncached(Class<T> classType, String propName) {
    if (propName.startsWith("_")) {
        propName = propName.substring(1);
    }/*w  w w .  j  ava 2 s.co m*/
    for (Method method : classType.getDeclaredMethods()) {
        XmlElement xmlElement = method.getAnnotation(XmlElement.class);
        if (xmlElement != null && xmlElement.name() != null && xmlElement.name().equals(propName)) {
            return method;
        }
        XmlAttribute xmlAttribute = method.getAnnotation(XmlAttribute.class);
        if (xmlAttribute != null && xmlAttribute.name() != null && xmlAttribute.name().equals(propName)) {
            return method;
        }
    }
    String getterName = "get" + StringUtils.capitalize(propName);
    try {
        return classType.getDeclaredMethod(getterName);
    } catch (NoSuchMethodException e) {
        // nothing found
    }
    getterName = "is" + StringUtils.capitalize(propName);
    try {
        return classType.getDeclaredMethod(getterName);
    } catch (NoSuchMethodException e) {
        // nothing found
    }
    Class<? super T> superclass = classType.getSuperclass();
    if (superclass.equals(Object.class)) {
        return null;
    }
    return findPropertyGetter(superclass, propName);
}

From source file:com.heliosphere.demeter.base.runner.AbstractRunner.java

/**
 * Initializes the runner configuration annotation.
 * <hr>/*  w w  w . j av  a 2s.  c om*/
 * @throws RunnerException Thrown in case an error occurred while trying to initialize the runner.
 * @see RunnerConfig
 */
@SuppressWarnings({ "rawtypes", "unchecked", "nls" })
private final void initializeRunnerConfigAnnotation() throws RunnerException {
    for (Annotation annotation : this.getClass().getAnnotations()) {
        Class<? extends Annotation> type = annotation.annotationType();
        if (type == RunnerConfig.class) {
            for (Method method : type.getDeclaredMethods()) {
                Object value;
                try {
                    value = method.invoke(annotation, (Object[]) null);
                    if (method.getName().equals("processorClass")) {
                        this.processorClass = (Class<? extends IProcessor>) value;
                    } else {
                        if (method.getName().equals("enumParameterClass")) {
                            this.enumParameterClass = (Class) value;
                        } else {
                            if (method.getName().equals("threadCount")) {
                                this.threadCount = ((Integer) value).intValue();
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RunnerException(String.format("Unable to initialize runner: %1s due to: %2s",
                            this.getClass().getName(), e.getMessage()));
                }
            }
        }
    }
}

From source file:com.xutils.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;//from w w w.j av  a  2s.  c o m
    }

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid id(" + viewInject.value() + ") for @ViewInject!"
                                + handlerType.getSimpleName());
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    }

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    }

    injectObject(handler, handlerType.getSuperclass(), finder);
}